开发者

Java string.split - by multiple character delimiter [duplicate]

开发者 https://www.devze.com 2023-04-06 11:48 出处:网络
This question already has answers here: How do I split a string in Java? (39 answers) Closed 7 years ago.
This question already has answers here: How do I split a string in Java? (39 answers) Closed 7 years ago.

I would like to parse entire file based on all the possible delimiters like commas, colon, semi colons, periods, spaces, hiphens etcs.

Suppose I have a hypothetical string l开发者_JAVA技巧ine "Hi,X How-how are:any you?" I should get output array with items Hi,X,How,how,are,any and you.

How do I specify all these delimiter in String.split method?

Thanks in advance.


String.split takes a regular expression, in this case, you want non-word characters (regex \W) to be the split, so it's simply:

String input = "Hi,X How-how are:any you?";
String[] parts = input.split("[\\W]");

If you wanted to be more explicit, you could use the exact characters in the expression:

String[] parts = input.split("[,\\s\\-:\\?]");
0

精彩评论

暂无评论...
验证码 换一张
取 消