我想提取单词形成一个段落串。我找了很多地方,但没有找到相对的材料。我想提取长度为4的单词,从
"我想在我老的时候有很多钱,可能是e1X2"
我想用
List<String> words = new ArrayList<String>();
String s = "I want to have alot of moneys when I am older probably.";
Pattern p = Pattern.compile("[a-zA-Z']{4,}");
Matcher m = p.matcher(s);
while (m.find()) {
words.add(m.group());
}
System.out.println(words);
我现在得到的输出是
[want, have, alot, moneys, when, older, probably]
但输出必须是
[want, have, alot, when]
更简单的方法得到的结果。
List<String> words=new ArrayList<String>();
String s="I want to have alot of of moneys when I am older probably";
String str[]=s.split(" ");
for(int i=0;i<str.length;i++)
{
if(str[i].length()==4)
words.add(str[i]);
}
System.out.print(words);
试试。
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
String s = "I want to have alot of moneys when I am older probably.";
Pattern p = Pattern.compile("\\b\\w{4}\\b");
Matcher m = p.matcher(s);
while (m.find()) {
words.add(m.group());
}
System.out.println(words);
}
输出: [want, have, alot, when]
解释:
\b
匹配一个词的边界。你想用regex做?
因为你没有放上表示组的"()",就像你调用 "m.group() "一样,你需要这样的语法。
在这里使用你的regex。regex101. 之后把它放在你的Java程序中。
你也可以将字符串用空格分割,然后只用所需长度的元素过滤所得到的数组。
在你的regex中,你需要看看后面和前面的内容
你的原创。
Pattern p = Pattern.compile("[a-zA-Z']{4,}");
前面和后面都有看头和看尾
Pattern p = Pattern.compile("(?=\s)[a-zA-Z']{4,}(?=\s)");
现在增加了前面和后面的内容 可能会出现字符串的开头和结尾不匹配的问题。在匹配的字符串两边加一个空格,应该就可以了。
一个解决方案,使用 溪流API
/* Required imports:
* import java.util.Arrays;
* import java.util.List;
* import java.util.stream.Collectors;
*/
List<String> words = Arrays.stream(text.split("\\b"))
.filter(word -> word.length() == 4)
.collect(Collectors.toList());
文本被分割成单个单词。只有长度为4的单词才会通过过滤器。所有的四个字母的单词都被收集到一个列表中。