Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

The Java official documentation states:

The string "boo:and:foo", for example, yields the following results with these expressions Regex Result :

{ "boo", "and", "foo" }"

And that's the way I need it to work. However, if I run this:

public static void main(String[] args){

        String test = "A|B|C||D";

        String[] result = test.split("|");

        for(String s : result){

            System.out.println(">"+s+"<");

        }

    }

it prints:

><

>A<

>|<

>B<

>|<

>C<

>|<

>|<

>D<

Which is far from what I would expect:

>A<

>B<

>C<

><

>D<

Why is this happening?

1 Answer

0 votes
by (46k points)

Use proper escaping: string.split("\\|")

Or the helper Pattern.quote() which has been created for exactly this purpose:

string.split(Pattern.quote("|"))

which works with arbitrary input strings. Very useful when you need to quote / escape user input.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Aug 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...