4

I have following code to split a string:

String s = "100$ali$Rezaie" ;
String[] ar = s.split("$") ;

But it doesn't work. Why?

Thanks for any suggestion.

4

3 に答える 3

13

Because public String[] split(String regex) accepts Regex as an argument and not a String.

$ is a meta-character that has a special meaning.

You should escape this $: \\$.

By escaping this, you're telling split to treat $ as the String $ and not the Regex $.
Note that escaping a String is done by \, but in Java \ is wrote as \\.

Alternative solution is to use Pattern#quote that "Returns a literal pattern String for the specified String:

String[] ar = s.split(Pattern.quote("$"))

于 2013-10-17T11:33:24.157 に答える