为什么字符串。分割管需要转义吗?

时间:2022-11-16 22:07:31

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()方法转义管道字符吗?

3 个解决方案

#1


175  

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.

字符串。split期望一个正则表达式参数。未转义的|被解析为regex,意思是“空字符串或空字符串”,这不是您的意思。

#2


76  

Because the syntax for that parameter to split is 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的特殊含义,'\|'表示一个字面的'|',所以字符串"\ |"表示正则表达式'\|',意思是与字符'|'匹配。

#3


6  

You can simply do this:

你可以这么做:

String[] arrayString = yourString.split("\\|");

#1


175  

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.

字符串。split期望一个正则表达式参数。未转义的|被解析为regex,意思是“空字符串或空字符串”,这不是您的意思。

#2


76  

Because the syntax for that parameter to split is 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的特殊含义,'\|'表示一个字面的'|',所以字符串"\ |"表示正则表达式'\|',意思是与字符'|'匹配。

#3


6  

You can simply do this:

你可以这么做:

String[] arrayString = yourString.split("\\|");