Question

Why can't I split a string with the dollar sign?

I want to split a string which has content like this:

a$b$c

but when I use:

String data=...
data.split("$");

it does not recognize $ and do not split string but when I replace $ by some Letter like X it works. does anyone has any Idea?

 45  52989  45
1 Jan 1970

Solution

 107

The split function takes a regular expression, not a string, to match. Your regular expression uses a special character - in this case '$' - so you would need to change it to escape that character:

String line = ...
String[] lineData = line.split("\\$");

Also note that split returns an array of strings - Strings are immutable, so they cannot be modified. Any modifications made to the String will be returned in a new String, and the original will not be changed. Hence the lineData = line.split("\\$"); above.

2010-01-30

Solution

 15

The split method accept a String as the first parameter that is then interpreted as a Regular Expression.

The dollar sign is a specific operator in regular expressions and so you have to escape it this way to get what you want:

String data = ...
String[] parts = data.split("\\$");

Or, if the delimiter may change you can be more general this way:

String data = ...
String[] parts = data.split(java.util.regex.Pattern.quote("$"));
2010-01-30