简体   繁体   中英

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:


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

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 es, st, and the last one after the final t.)

你必须使用两个反斜杠,它应该工作正常:这是一个例子:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM