Why can't I split a string with the dollar sign?
Solution 1:
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.
Solution 2:
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("$"));
Solution 3:
split()
uses a regular expression as parameter. You have to call split( "\\$" )
, because $
is the regular expression for "end of line".
Solution 4:
$ is a special character in regular expressions representing the end of the line. To match a dollar sign, use "\\$"
.
Solution 5:
String.split() in Java takes a String argument which is a regular expression. The '$' character in a regex means the end of a line. You can use an escape sequence ("\\$") if you are looking for a dollar sign in the string.
Sources:
String - Java API
Pattern - Java API