Strange split string behavior

Consider these simple lines of code:

public class Main {

    public static void main(String[] args) {

        String string = "Lorem,ipsum,dolor,sit,amet";
        String[] strings = string.split(",");

        for (String s : strings) {
            System.out.println(s);
        }
    }
}

As expected, the output is as follows:

Lorem
ipsum
dolor
sit
amet

Now, consider a version of the previous code in which I simply turned ,into |:

public class Main {

    public static void main(String[] args) {

        String string = "Lorem|ipsum|dolor|sit|amet";
        String[] strings = string.split("|");

        for (String s : strings) {
            System.out.println(s);
        }
    }
}

I expect the same exact conclusion, but the strange thing is this:

L
o
r
e
m
|
i
p
s
u
m
|
d
o
l
o
r
|
s
i
t
|
a
m
e
t

What's wrong?

+4
source share
1 answer

The String # split () method accepts a regular expression, but |has a special meaning in the regular expression.

To see the expected result, follow |.

String[] splits=string.split("\\|");

Or you can use a class Patternto avoid clutter.

String[] splits= string.split(Pattern.quote("|"));
+7
source

Source: https://habr.com/ru/post/1606073/


All Articles