在 Java 中查找包含 3 个字母的单词

Find words with 3 letters in Java

我想找到每个元素中包含 3 个字母的所有单词。

中我找到了正确的正则表达式,但我知道我正试图让它在 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);
    }
}

在我的例子中,我想输出 catdog,但我只得到一个空输出。

  1. 您必须转义反斜杠,即 \b 而不是 \b:

    Pattern p = Pattern.compile("\b[a-zA-Z]{3}\b");
    
  2. 创建匹配器并使用 findgroup 查找并显示下一个匹配组:

    for (String s : input) {
        Matcher m = p.matcher(s);
        while (m.find()) {
            System.out.println(m.group());
        }
    }