部分匹配会改变Matcher的位置

Cut*_*ter 9 java regex pattern-matching

使用Matcher的 find()方法时,部分匹配返回false,但匹配器的位置仍会移动.后续调用find()省略了那些部分匹配的字符.

部分匹配的示例:"[0-9]+:[0-9]"针对输入的模式"a3;9".此模式与输入的任何部分都不匹配,因此find()返回false,但子模式"[0-9]+"匹配"3".如果我们此时更改模式并find()再次调用,则不会测试新匹配项左侧的字符,包括部分匹配项.

请注意,模式"[0-9]:[0-9]"(没有量词)不会产生这种效果.

这是正常的行为吗?

示例:在第一个for循环中,第三个模式[0-9]与字符匹配"9","3"不会报告为匹配.在第二个循环中,模式[0-9]与字符匹配"3".

import java.util.regex.*;

public class Test {
    public static void main(String[] args) {
        final String INPUT = "a3;9";
        String[] patterns = {"a", "[0-9]+:[0-9]", "[0-9]"};

        Matcher matcher = Pattern.compile(".*").matcher(INPUT);

        System.out.printf("Input: %s%n", INPUT);
        matcher.reset();
        for (String s: patterns)
            testPattern(matcher, s);

        System.out.println("=======================================");

        patterns = new String[] {"a", "[0-9]:[0-9]", "[0-9]"};
        matcher.reset();
        for (String s: patterns)
            testPattern(matcher, s);
    }

    static void testPattern(Matcher m, String re) {     
        m.usePattern(Pattern.compile(re));
        System.out.printf("Using regex: %s%n", m.pattern().toString());

        // Testing for pattern
        if(m.find())
            System.out.printf("Found %s, end-pos: %d%n", m.group(), m.end());
    }
}
Run Code Online (Sandbox Code Playgroud)

Joo*_*gen 1

Matcher 提出了三种不同类型的匹配操作(参见 javadoc) -matches对于整个输入匹配 -find对于跳过不匹配的遍历 -lookingAt从序列的开头进行部分匹配

lookingAt当通过调用等找到模式时matcher.region(matcher.end(), matcher.regionEnd()),可以将其用于连续模式。

(大部分功劳都归功于OP本人)