在正则表达式前面加上\G。 Pattern 的 Javadoc 说:
\G - 上一场比赛结束
当然,在第一场比赛中,“上一场比赛的结束”就是输入的开始。
这确保了正则表达式匹配都是连续的,从输入的开头开始。并不意味着正则表达式会到达输入的末尾,您必须自己检查。
例子
public static void main(String[] args) {
test("abc");
test(" foo foo bar");
test(" foo foo bad");
test(" foo bad foo");
}
static void test(String input) {
System.out.println("'" + input + "'");
int lastEnd = 0;
Matcher m = Pattern.compile("\\G\\s+(foo|bar)").matcher(input);
while (m.find()) {
System.out.printf(" g0='%s' (%d-%d), g1='%s' (%d-%d)%n",
m.group(), m.start(), m.end(),
m.group(1), m.start(1), m.end(1));
lastEnd = m.end();
}
if (lastEnd == input.length())
System.out.println(" OK");
else
System.out.println(" Incomplete: Last match ended at " + lastEnd);
}
输出
'abc'
Incomplete: Last match ended at 0
' foo foo bar'
g0=' foo' (0-4), g1='foo' (1-4)
g0=' foo' (4-8), g1='foo' (5-8)
g0=' bar' (8-12), g1='bar' (9-12)
OK
' foo foo bad'
g0=' foo' (0-4), g1='foo' (1-4)
g0=' foo' (4-8), g1='foo' (5-8)
Incomplete: Last match ended at 8
' foo bad foo'
g0=' foo' (0-4), g1='foo' (1-4)
Incomplete: Last match ended at 4
为了比较,在正则表达式中没有\G,该代码的输出将是:
'abc'
Incomplete: Last match ended at 0
' foo foo bar'
g0=' foo' (0-4), g1='foo' (1-4)
g0=' foo' (4-8), g1='foo' (5-8)
g0=' bar' (8-12), g1='bar' (9-12)
OK
' foo foo bad'
g0=' foo' (0-4), g1='foo' (1-4)
g0=' foo' (4-8), g1='foo' (5-8)
Incomplete: Last match ended at 8
' foo bad foo'
g0=' foo' (0-4), g1='foo' (1-4)
g0=' foo' (8-12), g1='foo' (9-12)
OK
如您所见,最后一个示例无法检测到文本 bad 被跳过。