How to get the first match string using Regex

I have the following 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());
    }
  }
} 

Output:

photo.jpg
photo2.jpg

I would like to select the first match, so only photo.jpg , and skip the second photo2.jpg , I tried matcher.group (0) , but it didn’t work, any idea how to do this, thanks.

+3
source share
1 answer

Stop iteration after the first match. Change whiletoif

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

All Articles