我想找到每个元素中包含 3 个字母的所有单词。
在 this post我找到了正确的正则表达式,但我知道我正在尝试让它在 Java 中工作。
Set<String> input = new HashSet<String>();
input.add("cat 123");
input.add("monkey");
input.add("dog");
Pattern p = Pattern.compile("\b[a-zA-Z]{3}\b");
for (String s : input) {
if (p.matcher(s).matches()) {
System.out.println(s);
}
}
就我而言,我希望把 cat
和 dog
放掉,但我只得到一个空的输出。
最佳答案
您必须转义反斜杠,即
\\b
而不是\b
:Pattern p = Pattern.compile("\\b[a-zA-Z]{3}\\b");
创建匹配器并使用
find
和group
查找并显示下一个匹配的组:for (String s : input) { Matcher m = p.matcher(s); while (m.find()) { System.out.println(m.group()); } }
关于java - 在 Java 中查找包含 3 个字母的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33023575/