gpt4 book ai didi

java - 让 find() 在 java 的正则表达式中多次查找

转载 作者:行者123 更新时间:2023-12-02 09:07:27 24 4
gpt4 key购买 nike

我需要 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);

最佳答案

您必须为每场比赛调用 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

关于java - 让 find() 在 java 的正则表达式中多次查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59699269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com