Java 为什么 String.split 需要管道分隔符才能转义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9808689/
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
Why does String.split need pipe delimiter to be escaped?
提问by starthis
I am trying to parse a file that has each line with pipe delimited values. It did not work correctly when I did not escape the pipe delimiter in split method, but it worked correctly after I escaped the pipe as below.
我正在尝试解析一个文件,该文件的每一行都带有管道分隔值。当我没有在 split 方法中转义管道分隔符时,它没有正常工作,但是在我转义管道后它正常工作,如下所示。
private ArrayList<String> parseLine(String line) {
ArrayList<String> list = new ArrayList<String>();
String[] list_str = line.split("\|"); // note the escape "\" here
System.out.println(list_str.length);
System.out.println(line);
for(String s:list_str) {
list.add(s);
System.out.print(s+ "|");
}
return list;
}
Can someone please explain why the pipe character needs to be escaped for the split()
method?
有人可以解释为什么需要为该split()
方法转义管道字符吗?
采纳答案by Louis Wasserman
String.split
expects a regular expression argument. An unescaped |
is parsed as a regex meaning "empty string or empty string," which isn't what you mean.
String.split
需要一个正则表达式参数。未转义的|
被解析为正则表达式,意思是“空字符串或空字符串”,这不是您的意思。
回答by dlamblin
Because the syntax for that parameter to splitis a regular expression, where in the '|' has a special meaning of OR, and a '\|' means a literal '|' so the string "\\|" means the regular expression '\|' which means match exactly the character '|'.
因为要拆分的那个参数的语法是一个正则表达式,其中的“|” 有 OR 的特殊含义,还有一个 '\|' 表示文字“|” 所以字符串“\\|” 表示正则表达式'\|' 这意味着完全匹配字符“|”。
回答by Ravinath
You can simply do this:
你可以简单地这样做:
String[] arrayString = yourString.split("\|");