Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot split string with $ in Java

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.

like image 486
Avinash Mishra Avatar asked Jul 14 '15 08:07

Avinash Mishra


3 Answers

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("$"));
like image 168
Uli Avatar answered Oct 02 '22 04:10

Uli


You have to escape "$":

arrStr = str.split("\\$");
like image 23
VWeber Avatar answered Oct 02 '22 02:10

VWeber


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

like image 43
E Do Avatar answered Oct 02 '22 03:10

E Do