Reputation: 43
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());
}
}
}
The Output is:
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 not worked, Any idea how to do that, Thanks.
Upvotes: 4
Views: 4232
Reputation: 124215
Stop iterating after first match. Change while
to if
if (matcher.find()) {
System.out.println(matcher.group());
}
Upvotes: 5