8

I'm trying to split a line of text into multiple parts. Each element of the text is separated by a period. I'm using string.split("."); to split the text into an array of Strings, but not getting anywhere.

Here is a sample of the code:

String fileName = "testing.one.two";

String[] fileNameSplit = fileName.split(".");

System.out.println(fileNameSplit[0]);

The funny thing is, when I try ":" instead of ".", it works? How can I get it to work for a period?

Juvanis
  • 25,366
  • 5
  • 65
  • 85
CodyBugstein
  • 19,435
  • 57
  • 179
  • 333

6 Answers6

33

String.split() accepts a regular expression (regex for short) and dot is a special char in regexes. It means "match all chars except newlines". So you must escape it with a leading backslash. But the leading backslash is a special character in java string literals. It denotes an escape sequence. So it must be escaped too, with another leading backslash. Like this:

fileName.split("\\.");
Asaph
  • 154,284
  • 25
  • 189
  • 193
6

Try this one: fileName.split("\\.");

Juvanis
  • 25,366
  • 5
  • 65
  • 85
  • Still not working. The output is _testing.one.two_ when I want it to be _testing_ – CodyBugstein Nov 19 '12 at 19:22
  • @Imray This is called escape sequence. '\\.' => It's a regex that matches a literal '.' character in Java. You escape '.' with one slash and escape that slash with a second slash. – Juvanis Nov 19 '12 at 19:26
3
fileName.split(".");

should be

fileName.split("\\.");

. is special character and split() accepts regex. So, you need to escape the special characters.

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. Please read this documentation.

kosa
  • 64,776
  • 13
  • 121
  • 163
3

It's because the argument to split is a regular expression, and . means basically any character. Use "\\." instead of "." and it should work fine.

The regular expression for a literal period (as opposed to the any-character .) is \. (using the \ escape character forces the literal interpretation).

And, because it's within a string where \ already has special meaning, you need to escape that as well.

paxdiablo
  • 814,905
  • 225
  • 1,535
  • 1,899
1

You need to escape the "." character because split accept regular expressions and the . means any character, so for saying to the split method to split by point you must escape it like this:

String[] array = string.split('\\.');
ChuyAMS
  • 470
  • 2
  • 9
0

The split() takes in param a regex

Try.using

String[] fileNameSplit = fileName.split("\\.");
Mukul Goel
  • 8,426
  • 6
  • 35
  • 73