Samiey Mehdi
Samiey Mehdi

Reputation: 9424

Why $ not work in split method?

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.

Upvotes: 4

Views: 143

Answers (3)

Reimeus
Reimeus

Reputation: 159844

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

Upvotes: 6

devnull
devnull

Reputation: 123608

split takes a regex as an argument.

public String[] split(String regex)

Splits this string around matches of the given regular expression.

You need to escape the $ sign.

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

You need to say \\ because the \ needs to be escaped too!

Upvotes: 5

Maroun
Maroun

Reputation: 95998

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

Upvotes: 13

Related Questions