Java line breaks

When I split the string "1|2|3|4"with String.split("|"), I get 8 elements in the array instead of 4. If I use "\\|", the result will be correct. I guess this is something to do with regular expressions. Can anyone explain this?

+3
source share
3 answers

You're right. |- a special character for alternation. A regular expression |means "empty string or empty string". Thus, it will be divided into all empty lines, resulting in 1 element for each character in the line. Shielding \|makes it normal.

+7

, Splitter Guava. , ..

Iterable<String> split = Splitter.on('|').split("1|2|3|4");
+3

|is ORin the Java regular expression syntax, basically splitting 1|2|3|4by |equal value String#split()to “split this line between blank OR blank”), which means that it is split after every character that you are in the original string.

+1
source

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


All Articles