Jon
Jon

Reputation: 43

Java String split regex not working as expected

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

Upvotes: 4

Views: 944

Answers (3)

Sunil Kapil
Sunil Kapil

Reputation: 1040

You have to use two backslashes and it should work fine: Here is example:

String[] parts = string.split("\\.",-1);

Upvotes: 2

Jerome
Jerome

Reputation: 8447

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.)

Upvotes: 6

kokosing
kokosing

Reputation: 5601

Everything is ok. "Test" is split on each character, and so between them there is no character. If you want iterate your string over each character you can use charAt and length methods.

Upvotes: 1

Related Questions