3
拿到第一个匹配的字符串我有如下因素代码:如何使用正则表达式
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