首页 > 解决方案 > 让 find() 在 java 的正则表达式中找到不止一次

问题描述

我需要 find() 多次查找。例如,在下面的正则表达式中,它只会得到“i am cool1”,但我也希望它得到“i am cool2”和“i am cool3”。我该怎么做?

Pattern pattern = Pattern.compile("i am cool([0-9]{1})", Pattern.CASE_INSENSITIVE);
String theString = "i am cool1 text i am cool2 text i am cool3 text";
Matcher matcher = pattern.matcher(theString);
matcher.find();
whatYouNeed = matcher.group(1);

标签: javaregexfind

解决方案


您必须为每场比赛调用 find() 。您可以使用 group() 获得整个匹配(不带索引)。

    Pattern pattern = Pattern.compile("i am cool([0-9]{1})", Pattern.CASE_INSENSITIVE);
    String theString = "i am cool1 text i am cool2 text i am cool3 text";
    Matcher matcher = pattern.matcher(theString);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

这将打印

i am cool1
i am cool2
i am cool3

推荐阅读