如何使用正则表达式获取第一个匹配的字符串

4

I have folowing code:

public class RegexTestPatternMatcher {
  public static final String EXAMPLE_TEST = "This is my first photo.jpg string and this my second photo2.jpg String";

  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("\\w+\\.jpg");
    Matcher matcher = pattern.matcher(EXAMPLE_TEST);
    // check all occurance
    while (matcher.find()) {
      System.out.println(matcher.group());
    }
  }
} 

输出结果如下:
photo.jpg
photo2.jpg

我想选择第一个匹配项,只需要photo.jpg,跳过第二个photo2.jpg,我尝试了matcher.group(0),但没有效果,您有任何想法如何做到这一点吗?谢谢。


只需删除循环并调用matcher.find()matcher.group()一次即可? - Jerry
1个回答

5

在第一次匹配后停止迭代。将 while 更改为 if

if (matcher.find()) {
  System.out.println(matcher.group());
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接