Java String split("|" ) 方法调用无法正常工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24775817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java String split("|" ) method call not working correctly
提问by user2677600
public class SplitStr {
public static void main(String []args) {
String str1 = "This | is | My | Account | For | Java|";
String str2 = "This / is / My / Account / For / Java/";
// String[] arr = str.split("|");
for(String item : str1.split("|")) {
System.out.print(item);
}
}
}
The program is working correctly with String str2 but it is not working with String str1 What are the possible flows in this program?
该程序在使用 String str2 时可以正常工作,但在使用 String str1 时无法正常工作 该程序中可能存在哪些流程?
回答by tobias_k
split
expects a regular expression, and since |
is a special character in regular expressions, you have to escape it. Try str.split("\\|")
. Example:
split
需要一个正则表达式,因为它|
是正则表达式中的一个特殊字符,所以你必须对它进行转义。试试str.split("\\|")
。例子:
>>> Arrays.asList("This | is | My | Account | For | Java|".split("\|"));
[This , is , My , Account , For , Java]
回答by Jae Heon Lee
String#split()
expects a regular expression as the first argument and |
is a control character in regex.
String#split()
期望正则表达式作为第一个参数,并且|
是正则表达式中的控制字符。
To make regex parser understand that you mean to split by the literal |
, you need to pass \|
to the regex parser. But \
is a control character in Java string literals. So, to make Java compiler understand that you want to pass \|
to the regex parser, you need to pass "\\|"
to the String#split()
method.
为了让正则表达式解析器理解你的意思是按文字分割|
,你需要传递\|
给正则表达式解析器。但是\
是 Java 字符串文字中的控制字符。所以,为了让 Java 编译器明白你想传递\|
给正则表达式解析器,你需要传递"\\|"
给String#split()
方法。
回答by Ruchira Gayan Ranaweera
Use
用
str1.split("\|")
instead of
代替
str1.split("|")
You need to escape |
你需要逃离 |