Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why $ not work in split method?

Tags:

java

string

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.

like image 683
Samiey Mehdi Avatar asked Nov 28 '22 07:11

Samiey Mehdi


2 Answers

split takes a regex as an argument. $ is a meta-character used as an anchor to match end of a String. The character should be escaped to split on a literal $ String

String[] ar = s.split("\\$");
like image 24
Reimeus Avatar answered Dec 04 '22 16:12

Reimeus


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("$"))

like image 195
Maroun Avatar answered Dec 04 '22 15:12

Maroun