【发布时间】:2021-05-18 21:07:36
【问题描述】:
我想在单词边界中分割一个字符串,因此现在我正在考虑那个空格,一个','和一个'。'或者 '!'表示单词的边界。
在以下示例中:
String text = "This is, just a text to be used, for testing purpose. Nothing more!";
String[] words = text.split("[\\s+,.!]");
for(String w: words) {
System.out.println(w);
}
打印出来:
This
is
just
a
text
to
be
used
for
testing
purpose
Nothing
more
如您所见,以, 或. 或! 结尾的词有空词
但是如果我在我的正则表达式中添加一个+:
String[] words = text.split("[\\s+,.!]+");
for(String w: words) {
System.out.println(w);
}
This
is
just
a
text
to
be
used
for
testing
purpose
Nothing
more
空话不存在。为什么需要+ 才能避免空话?
【问题讨论】: