然而,该主题令人困惑,例如,
final String pattern = "(abc)";
final String content = "dabcef";
Matcher m = Pattern.compile(pattern).matcher(content);
m.find()肯定会返回true。
我想知道是否可以只处理一次字符,这意味着
“dab” - >没找到,“cef” - >没找到,结束。
谢谢!
编辑:
实际上我想查找所有匹配项而不是仅检查是否匹配。例如,
abc abc def abc dab cef(实际上没有空格)
将匹配^(。{3})*?(abc),但只有一次。我期待3场比赛。
谢谢!
答案 0 :(得分:4)
怎么样:
final String pattern = "^(.{3})*(abc)";
答案 1 :(得分:0)
我通过移动开始索引找到了解决方案。感谢@Oil的建议!
public static void main(String[] args) {
final String pattern1 = "^(.{3})*?(abc)";
final String content1 = "efabcabcdabcefaabcdfabce"; // two matches
final String content2 = "abcabcdabcefabc"; // three matches
Matcher mStart = Pattern.compile(pattern1).matcher(content1);
while (mStart.find()) {
System.out.println(mStart.group(mStart.groupCount()));
System.out.println(mStart.start() + ", " + mStart.end());
mStart = mStart.region(mStart.end(), mStart.regionEnd());
}
//-----------------------------
System.out.println("------------------------");
mStart = Pattern.compile(pattern1).matcher(content2);
while (mStart.find()) {
System.out.println(mStart.group(mStart.groupCount()));
System.out.println(mStart.start() + ", " + mStart.end());
mStart = mStart.region(mStart.end(), mStart.regionEnd());
}
}