6

I was just doodling on eclipse IDE and written following code.

String str = new String("A$B$C$D");
String arrStr[] = str.split("$");
for (int i = 0; i < arrStr.length; i++) {
    System.out.println("Val: "+arrStr[i]);
}

I was expecting output like: Val: A Val: B Val: C Val: D
But instead of this, I got output as

Val: A$B$C$D Why? I am thinking may be its internally treated as a special input or may be its like variable declaration rules.

Holger
  • 285,553
  • 42
  • 434
  • 765
Avinash Mishra
  • 1,346
  • 3
  • 21
  • 41
  • possible duplicate of [Why does String.split need pipe delimiter to be escaped?](http://stackoverflow.com/questions/9808689/why-does-string-split-need-pipe-delimiter-to-be-escaped) – Raedwald Jul 17 '15 at 11:41

5 Answers5

11

The method String.split(String regex) takes a regular expression as parameter so $ means EOL.

If you want to split by the character $ you can use

String arrStr[] = str.split(Pattern.quote("$"));
Uli
  • 1,390
  • 1
  • 14
  • 28
  • A little overhead for escaping the dollar symbol ;) – VWeber Jul 14 '15 at 08:58
  • 3
    You don't have to think about how to escape any character => less error prone. – Uli Jul 14 '15 at 09:00
  • But split method will work if I use different characters like "_" or ",". – Avinash Mishra Jul 14 '15 at 09:00
  • 2
    @Avinash: "_" and "," are no special regexp characters. They are treated as they are. Please read the javadoc for regular expressions: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html – Uli Jul 14 '15 at 09:11
8

You have to escape "$":

arrStr = str.split("\\$");
VWeber
  • 1,261
  • 2
  • 12
  • 34
4

You have used $ as regex for split. That character is already defined in regular expression for "The end of a line" (refer this). So you need to escape the character from actual regular expression and your splitting character should be $.

So use str.split("\\$") instead of str.split("$") in your code

Estimate
  • 1,421
  • 1
  • 18
  • 31
3

The split() method accepts a string that resembles a regular expression (see Javadoc). In regular expressions, the $ char is reserved (matching "the end of the line", see Javadoc). Therefore you have to escape it as Avinash wrote.

String arrStr[] = str.split("\\$");

The double-backslash is to escape the backslash itself.

Gerald Mücke
  • 10,724
  • 2
  • 50
  • 67
1

Its simple. The "$" character is reserved that means you need to escape it.

String str = new String("A$B$C$D");
String arrStr[] = str.split("\\$");
for (int i = 0; i < arrStr.length; i++) {
    System.out.println("Val: "+arrStr[i]);
}

That should work fine. So whenever something like this happens escape the character!

petritz
  • 182
  • 1
  • 9