This question already has an answer here:
这个问题已经有了答案:
- How to split a string in Java 31 answers
- 如何在Java 31中拆分一个字符串?
I would like to parse entire file based on all the possible delimiters like commas, colon, semi colons, periods, spaces, hiphens etcs.
我希望基于所有可能的分隔符(如逗号、冒号、半冒号、句点、空格、hiphens etcs)解析整个文件。
Suppose I have a hypothetical string line "Hi,X How-how are:any you?" I should get output array with items Hi,X,How,how,are,any and you.
假设我有一个假设的字符串“Hi,X how - are:any you?”我应该得到输出数组的项Hi,X,How, How, are,any和you。
How do I specify all these delimiter in String.split method?
如何在字符串中指定所有这些分隔符。分割方法?
Thanks in advance.
提前谢谢。
1 个解决方案
#1
23
String.split
takes a regular expression, in this case, you want non-word characters (regex \W
) to be the split, so it's simply:
字符串。split取一个正则表达式,在本例中,您希望非单词字符(regex \W)为split,因此它很简单:
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\\-:\\?]");
#1
23
String.split
takes a regular expression, in this case, you want non-word characters (regex \W
) to be the split, so it's simply:
字符串。split取一个正则表达式,在本例中,您希望非单词字符(regex \W)为split,因此它很简单:
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\\-:\\?]");