开发者

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?


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.


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


split() uses a regular expression as parameter. You have to call split( "\\$" ), because $ is the regular expression for "end of line".


$ is a special character in regular expressions representing the end of the line. To match a dollar sign, use "\\$".


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


You may have an issue with the uniCode characters for non-breaking spaces. Try...

String[] elements = myString.split("[\\s\\xA0]+"); //include uniCode non-breaking
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜