Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (4k points)

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.

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?

1 Answer

0 votes
by (46k points)
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.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...