Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string in Java

When I split the string "1|2|3|4" using the String.split("|") I get 8 elements in the array instead of 4. If I use "\\|" the result is proper. I am guessing this has something todo with regular expressions. Can anybody explain this?

like image 251
why should I tell you my name Avatar asked Sep 30 '26 04:09

why should I tell you my name


2 Answers

You're right. | is a special character for alternation. The regular expression | means "an empty string or an empty string". So it will split around all empty strings, resulting 1 element for each character in the string. Escaping it \| make it a normal character.

like image 126
kennytm Avatar answered Oct 01 '26 16:10

kennytm


If you want to split a string without using a regex, I'd recommend the Splitter class from Guava. It can split on fixed strings, regexes and more.

Iterable<String> split = Splitter.on('|').split("1|2|3|4");
like image 27
ColinD Avatar answered Oct 01 '26 18:10

ColinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!