为什么我不能用 Java 中的 $ 拆分字符串
Why I cannot split string with $ in Java
我只是在 eclipse IDE
上涂鸦并编写了以下代码。
String str = new String("A$B$C$D");
String arrStr[] = str.split("$");
for (int i = 0; i < arrStr.length; i++) {
System.out.println("Val: "+arrStr[i]);
}
我期待这样的输出:
瓦尔:一个
值:B
值:C
瓦尔:D
但不是这样,我得到的输出是
Val: A$B$C$D
为什么?我在想可能是它在内部被视为一个特殊的输入,或者可能是它的变量声明规则。
你必须转义“$”:
arrStr = str.split("\$");
方法 String.split(String regex)
将正则表达式作为参数,因此 $
表示 EOL。
如果你想按字符 $
分割,你可以使用
String arrStr[] = str.split(Pattern.quote("$"));
您已使用 $
作为拆分的正则表达式。该字符已在 "The end of a line" (refer this) 的正则表达式中定义。所以你需要从实际的正则表达式中转义字符,你的拆分字符应该是 $
.
所以在代码中使用 str.split("\$")
而不是 str.split("$")
split()
方法接受类似于正则表达式的字符串(请参阅 Javadoc). In regular expressions, the $
char is reserved (matching "the end of the line", see Javadoc)。因此你必须像 Avinash 写的那样逃避它。
String arrStr[] = str.split("\$");
双反斜杠是为了转义反斜杠本身。
很简单。 “$”字符是保留字符,这意味着您需要对其进行转义。
String str = new String("A$B$C$D");
String arrStr[] = str.split("\$");
for (int i = 0; i < arrStr.length; i++) {
System.out.println("Val: "+arrStr[i]);
}
那应该没问题。所以每当发生这样的事情时,逃避这个角色!
我只是在 eclipse IDE
上涂鸦并编写了以下代码。
String str = new String("A$B$C$D");
String arrStr[] = str.split("$");
for (int i = 0; i < arrStr.length; i++) {
System.out.println("Val: "+arrStr[i]);
}
我期待这样的输出:
瓦尔:一个
值:B
值:C
瓦尔:D
但不是这样,我得到的输出是
Val: A$B$C$D
为什么?我在想可能是它在内部被视为一个特殊的输入,或者可能是它的变量声明规则。
你必须转义“$”:
arrStr = str.split("\$");
方法 String.split(String regex)
将正则表达式作为参数,因此 $
表示 EOL。
如果你想按字符 $
分割,你可以使用
String arrStr[] = str.split(Pattern.quote("$"));
您已使用 $
作为拆分的正则表达式。该字符已在 "The end of a line" (refer this) 的正则表达式中定义。所以你需要从实际的正则表达式中转义字符,你的拆分字符应该是 $
.
所以在代码中使用 str.split("\$")
而不是 str.split("$")
split()
方法接受类似于正则表达式的字符串(请参阅 Javadoc). In regular expressions, the $
char is reserved (matching "the end of the line", see Javadoc)。因此你必须像 Avinash 写的那样逃避它。
String arrStr[] = str.split("\$");
双反斜杠是为了转义反斜杠本身。
很简单。 “$”字符是保留字符,这意味着您需要对其进行转义。
String str = new String("A$B$C$D");
String arrStr[] = str.split("\$");
for (int i = 0; i < arrStr.length; i++) {
System.out.println("Val: "+arrStr[i]);
}
那应该没问题。所以每当发生这样的事情时,逃避这个角色!