10

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,802
  • 5
  • 69
  • 87
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

6 Answers6

35

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
  • 159,146
  • 25
  • 197
  • 199
7

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

Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • 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
5
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
  • 65,990
  • 13
  • 130
  • 167
4

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
  • 854,327
  • 234
  • 1,573
  • 1,953
2

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
  • 480
  • 2
  • 9
1

The split() takes in param a regex

Try.using

String[] fileNameSplit = fileName.split("\\.");
Mukul Goel
  • 8,387
  • 6
  • 37
  • 77