Matches LookingAt And Find Differ

Pick the right Matcher entry point: matches demands the whole input, lookingAt anchors the prefix, find scans anywhere for the next hit.

JavaForm Validation

Code

snippet
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchModes {

    public static void main(String[] args) {
        Pattern sku = Pattern.compile("[A-Z]{2}-\\d{4}");
        String input = "XX-1234 and XX-9999";

        // matches:整个输入必须完全匹配——表单校验用这个
        System.out.println("matches  : " + sku.matcher("XX-1234").matches());
        System.out.println("matches  : " + sku.matcher(input).matches());

        // lookingAt:只锚定前缀,不要求吃完整输入
        System.out.println("lookingAt: " + sku.matcher(input).lookingAt());

        // find:从上次命中之后继续扫描,逐个取出所有命中
        Matcher m = sku.matcher(input);
        while (m.find()) {
            System.out.println("find     : " + m.group() + " at " + m.start());
        }
    }
}

Three entry points

Against the pattern [A-Z]{2}-\d{4}: matches() demands the entire input be consumed — true for the single SKU XX-1234, false for the combined string; lookingAt() anchors only the prefix, so it returns true for the combined string; find() scans forward from the last hit, reporting each match with group() and start().

The find loop

The while (m.find()) loop prints find : XX-1234 at 0 and find : XX-9999 at 15, demonstrating that successive find calls continue from where the previous one stopped.

Choosing correctly

Form validation wants matches; input-prefix checks want lookingAt; extraction or counting over free text wants find. Mixing them up produces silent acceptance or missed hits.

Interactive Tools for This Topic

FAQ

When should you prefer lookingAt over matches?
When only the beginning of the input must conform (a prefix protocol check); matches would reject input that carries extra trailing text.
How does successive find() behave?
Each call continues scanning from just after the previous match, which is why the loop reports both SKUs with their offsets.