什么正则表达式模式,我需要传递给String.split()
方法将字符串拆分成一个子字符串数组使用空格以及以下字符作为分隔符。 (" ! ", " , " , " ? " , " . " , " \ " , " _ " , " @ " , " ' ")
它也可以是上述字符与空格的组合。我已经试过这样的事情:如何在java中使用分隔符分割字符串?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class StringWordCount {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new IputStreamReader(System.in));
String string = bufferedReader.readLine();
String delimiter = "[,\\s]+|\\[!\\s]+|\\[?\\s]+|\\[.\\s]+|\\[_\\s]+|\\[_\\s]+|\\['\\s]+|\\[@\\s]+|\\!|\\,|\\?|\\.|\\_|\\'|\\@";
String[] words = string.split(delimiter);
System.out.println(words.length);
for(int i = 0; i<words.length; i++) {
System.out.println(words[i]);
}
}
}
上面的代码只生成了一些测试用例正确的输出,在其他情况下,也不会产生正确的one.For例如, 考虑下面的字符串,它没有得到预期的输出。
了它的输出:
23
Hello
thanks
for
attempting
this
problem
Hope
it
will
help
you
to
learn
java
Good
luck
and
have
a
nice
day
取而代之的是一个:
21
Hello
thanks
for
attempting
this
problem
Hope
it
will
help
you
to
learn
java
Good
luck
and
have
a
nice
day
正如你可以在第一个输出中看到,其留下的" ! "
和[space]
和组合空间上述组合的分隔符是\\[!\\s]
,对吗?
可能的重复[如何在Java中拆分字符串](http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Tushar
@Tushar和其他人:问题你称之为“重复”是由不知道split()的人发布的。这位提问者知道'split'并且无法正确地获取分隔符。这不是重复的。 – ajb
在给定场景下,StringTokenizer更合适。尽管它已被扫描器和拆分方法所取代。 –