Difference between matches() and find() in Java Regex

后端 未结 5 2021
感情败类
感情败类 2020-11-21 06:20

I am trying to understand the difference between matches() and find().

According to the Javadoc, (from what I understand), matches() will search the ent

5条回答
  •  温柔的废话
    2020-11-21 07:02

    matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find() multiple times might not be the same. In addition, by using find() you can call start() to return the position the substring was matched.

    final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
    System.out.println("Found: " + subMatcher.matches());
    System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
    System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
    System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
    System.out.println("Found: " + subMatcher.find());
    System.out.println("Found: " + subMatcher.find());
    System.out.println("Matched: " + subMatcher.matches());
    
    System.out.println("-----------");
    final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
    System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
    System.out.println("Found: " + fullMatcher.find());
    System.out.println("Found: " + fullMatcher.find());
    System.out.println("Matched: " + fullMatcher.matches());
    System.out.println("Matched: " + fullMatcher.matches());
    System.out.println("Matched: " + fullMatcher.matches());
    System.out.println("Matched: " + fullMatcher.matches());
    

    Will output:

    Found: false
    Found: true - position 4
    Found: true - position 17
    Found: true - position 20
    Found: false
    Found: false
    Matched: false
    -----------
    Found: true - position 0
    Found: false
    Found: false
    Matched: true
    Matched: true
    Matched: true
    Matched: true
    

    So, be careful when calling find() multiple times if the Matcher object was not reset, even when the regex is surrounded with ^ and $ to match the full string.

提交回复
热议问题