gpt4 book ai didi

java - 在Java中查找多个正则表达式匹配,禁止不匹配

转载 作者:行者123 更新时间:2023-12-02 01:07:36 26 4
gpt4 key购买 nike

我有一个 Java Pattern 例如 \s+(foo|bar) 来查找 foobar 的所有匹配项空格后的。使用匹配组我可以提取实际匹配的文本。

Pattern pattern=Pattern.compile("\\s+(foo|bar)");
Matcher matcher = pattern.match(someText);
while(matcher.find()) {
String value = matcher.group(1);
...
}

这适用于像 foo foo bar 这样的字符串(注意前面的空格),但它也可以匹配像 foo foo bad 这样的字符串。我怎样才能阻止匹配器匹配不匹配的后续字符运行,或者检测到字符被跳过或没有更多的剩余字符?换句话说,我希望匹配的整个字符串是与该模式匹配的后续字符串的序列。我如何保证这一点?

这里的要点是继续遍历字符串查找匹配项。我可以轻松地分割字符串,然后执行额外的比较,但我不希望产生多个正则表达式传递、数组/列表创建等的开销。

最佳答案

在正则表达式中添加 \G 前缀。 Pattern 的 Javadoc说:

\G - The end of the previous match

当然,在第一场比赛中,“上一场比赛的结束”就是输入的开始。

这确保正则表达式匹配都是连续的,从输入的开头开始。并不意味着正则表达式会到达输入的末尾,您必须自己检查。

示例

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

关于java - 在Java中查找多个正则表达式匹配,禁止不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59816862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com