Why can't I split the string with $ in Java

I just drew on the eclipse IDE and wrote the 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 expected an output like: Val: A Val: B Val: C Val: D
But instead, I got a conclusion like

Val: A$B$C$D Why? I think maybe it was interpreted internally as a special input, or it could be as rules for declaring variables.

+5
source share
5 answers

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

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

 String arrStr[] = str.split(Pattern.quote("$")); 
+9
source

You need to avoid the "$":

 arrStr = str.split("\\$"); 
+7
source

You used $ as regex for split. This character is already defined in the regular expression for "End of Line" ( see This ). Thus, you need to escape the character from the actual regular expression, and your separator character should be $ .

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

+3
source

The split() method accepts a string that looks like a regular expression (see Javadoc ). In regular expressions, $ char is reserved (the corresponding "end of line", see Javadoc ). Therefore, you should avoid this, as Avinash wrote.

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

Double backslash is a way out of backslash.

+3
source

Simple The "$" character is reserved, which means you need to avoid 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]); } 

This should work fine. So when something like this happens, run away from the character!

+1
source

All Articles