简体   繁体   English

为什么我不能用美元符号拆分字符串?

[英]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.它不识别 $ 并且不拆分字符串,但是当我用一些像 X 这样的字母替换 $ 时,它可以工作。 does anyone has any Idea?有没有人有任何想法?

The split function takes a regular expression, not a string, to match. split 函数采用正则表达式而不是字符串进行匹配。 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.还要注意 split 返回一个字符串数组 - 字符串是不可变的,所以它们不能被修改。 Any modifications made to the String will be returned in a new String, and the original will not be changed.对 String 所做的任何修改都将在新的 String 中返回,并且不会更改原始字符串。 Hence the lineData = line.split("\\\\$");因此lineData = line.split("\\\\$"); above.以上。

The split method accept a String as the first parameter that is then interpreted as a Regular Expression. split 方法接受一个字符串作为第一个参数,然后将其解释为正则表达式。

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. split()使用正则表达式作为参数。 You have to call split( "\\\\$" ) , because $ is the regular expression for "end of line".您必须调用split( "\\\\$" ) ,因为$是“行尾”的正则表达式。

String.split() in Java takes a String argument which is a regular expression. Java 中的 String.split() 接受一个 String 参数,它是一个正则表达式。 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 字符串- Java API

Pattern - Java API 模式- Java API

$ is a special character in regular expressions representing the end of the line. $ 是正则表达式中表示行尾的特殊字符。 To match a dollar sign, use "\\\\$" .要匹配美元符号,请使用"\\\\$"

You may have an issue with the uniCode characters for non-breaking spaces.对于不间断空格的 uniCode 字符,您可能会遇到问题。 Try...尝试...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM