Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String split regex not working as expected

Tags:

java

regex

The following Java code will print "0". I would expect that this would print "4". According to the Java API String.split "Splits this string around matches of the given regular expression". And from the linked regular expression documentation:

Predefined character classes
. Any character (may or may not match line terminators)

Therefore I would expect "Test" to be split on each character. I am clearly misunderstanding something.

System.out.println("Test".split(".").length); //0

like image 595
Jon Avatar asked Jan 23 '23 20:01

Jon


1 Answers

You're right: it is split on each character. However, the "split" character is not returned by this function, hence the resulting 0.

The important part in the javadoc: "Trailing empty strings are therefore not included in the resulting array. "

I think you want "Test".split(".", -1).length(), but this will return 5 and not 4 (there are 5 ''spaces'': one before T, one between T and e, others for e-s, s-t, and the last one after the final t.)

like image 131
Jerome Avatar answered Jan 25 '23 09:01

Jerome