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











up vote
203
down vote

favorite
48












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



According to the Javadoc, (from what I understand), matches() will search the entire string even if it finds what it is looking for, and find() will stop when it finds what it is looking for.



If that assumption is correct, I cannot see whenever you would want to use matches() instead of find(), unless you want to count the number of matches it finds.



In my opinion the String class should then have find() instead of matches() as an inbuilt method.



So to summarize:




  1. Is my assumption correct?

  2. When is it useful to use matches() instead of find()?










share|improve this question




















  • 2




    Be aware that calling find() multiple times may return different results for the same Matcher. See my answer below.
    – L. Holanda
    Aug 23 '13 at 18:02















up vote
203
down vote

favorite
48












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



According to the Javadoc, (from what I understand), matches() will search the entire string even if it finds what it is looking for, and find() will stop when it finds what it is looking for.



If that assumption is correct, I cannot see whenever you would want to use matches() instead of find(), unless you want to count the number of matches it finds.



In my opinion the String class should then have find() instead of matches() as an inbuilt method.



So to summarize:




  1. Is my assumption correct?

  2. When is it useful to use matches() instead of find()?










share|improve this question




















  • 2




    Be aware that calling find() multiple times may return different results for the same Matcher. See my answer below.
    – L. Holanda
    Aug 23 '13 at 18:02













up vote
203
down vote

favorite
48









up vote
203
down vote

favorite
48






48





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



According to the Javadoc, (from what I understand), matches() will search the entire string even if it finds what it is looking for, and find() will stop when it finds what it is looking for.



If that assumption is correct, I cannot see whenever you would want to use matches() instead of find(), unless you want to count the number of matches it finds.



In my opinion the String class should then have find() instead of matches() as an inbuilt method.



So to summarize:




  1. Is my assumption correct?

  2. When is it useful to use matches() instead of find()?










share|improve this question















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



According to the Javadoc, (from what I understand), matches() will search the entire string even if it finds what it is looking for, and find() will stop when it finds what it is looking for.



If that assumption is correct, I cannot see whenever you would want to use matches() instead of find(), unless you want to count the number of matches it finds.



In my opinion the String class should then have find() instead of matches() as an inbuilt method.



So to summarize:




  1. Is my assumption correct?

  2. When is it useful to use matches() instead of find()?







java regex






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 17 '16 at 6:24









evandrix

4,74222329




4,74222329










asked Dec 15 '10 at 12:50









Shervin Asgari

14.7k2580127




14.7k2580127








  • 2




    Be aware that calling find() multiple times may return different results for the same Matcher. See my answer below.
    – L. Holanda
    Aug 23 '13 at 18:02














  • 2




    Be aware that calling find() multiple times may return different results for the same Matcher. See my answer below.
    – L. Holanda
    Aug 23 '13 at 18:02








2




2




Be aware that calling find() multiple times may return different results for the same Matcher. See my answer below.
– L. Holanda
Aug 23 '13 at 18:02




Be aware that calling find() multiple times may return different results for the same Matcher. See my answer below.
– L. Holanda
Aug 23 '13 at 18:02












5 Answers
5






active

oldest

votes

















up vote
257
down vote



accepted










matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:



public static void main(String args) throws ParseException {
Pattern p = Pattern.compile("\d\d\d");
Matcher m = p.matcher("a123b");
System.out.println(m.find());
System.out.println(m.matches());

p = Pattern.compile("^\d\d\d$");
m = p.matcher("123");
System.out.println(m.find());
System.out.println(m.matches());
}

/* output:
true
false
true
true
*/


123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.






share|improve this answer



















  • 16




    This answer is misleading. matchers() is not simply a find() with implied surrounding ^ and $. Be aware that calling .find() more than once may have different results if not preceeded by reset(), while matches() will always return same result. See my answer below.
    – L. Holanda
    Nov 20 '15 at 22:35


















up vote
65
down vote













matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.






share|improve this answer

















  • 32




    You could say that matches(p) is the same as find("^" + p + "$") if that's any clearer.
    – jensgram
    Dec 15 '10 at 12:56






  • 3




    Just an example to clarify the answer: "[a-z]+" with string "123abc123" will fail using matches() but will succeed using find().
    – bezmax
    Dec 15 '10 at 12:57






  • 3




    @Max Exactly, "123abc123".matches("[a-z]+") will fail just as "123abc123".find("^[a-z]+$") would. My point was, that matches() goes for a complete match, just as find() with both start and end anchors.
    – jensgram
    Dec 15 '10 at 12:59








  • 4




    Pattern.compile("some pattern").matcher(str).matches() is equal to Pattern.compile("^some pattern$").matcher(str).find()
    – AlexR
    Dec 15 '10 at 13:09






  • 2




    @AlexR / @jensgram: ...("some pattern").matcher(str).matches() is not exactly equal to ...("^some pattern$").matcher(str).find() that's only true in the first call. See my answer below.
    – L. Holanda
    Aug 11 '16 at 17:55




















up vote
41
down vote













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.






share|improve this answer




























    up vote
    3
    down vote













    find() will consider the sub-string against the regular expression where as matches() will consider complete expression.



    find() will returns true only if the sub-string of the expression matches the pattern.



    public static void main(String args) {
    Pattern p = Pattern.compile("\d");
    String candidate = "Java123";
    Matcher m = p.matcher(candidate);

    if (m != null){
    System.out.println(m.find());//true
    System.out.println(m.matches());//false
    }
    }





    share|improve this answer






























      up vote
      2
      down vote













      matches(); does not buffer, but find() buffers. find() searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.



      That is why when you have a code like



      1:Pattern.compile("[a-z]");

      2:Pattern.matcher("0a1b1c3d4");

      3:int count = 0;

      4:while(matcher.find()){

      5:count++: }


      At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character] to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.






      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4450045%2fdifference-between-matches-and-find-in-java-regex%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        257
        down vote



        accepted










        matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:



        public static void main(String args) throws ParseException {
        Pattern p = Pattern.compile("\d\d\d");
        Matcher m = p.matcher("a123b");
        System.out.println(m.find());
        System.out.println(m.matches());

        p = Pattern.compile("^\d\d\d$");
        m = p.matcher("123");
        System.out.println(m.find());
        System.out.println(m.matches());
        }

        /* output:
        true
        false
        true
        true
        */


        123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.






        share|improve this answer



















        • 16




          This answer is misleading. matchers() is not simply a find() with implied surrounding ^ and $. Be aware that calling .find() more than once may have different results if not preceeded by reset(), while matches() will always return same result. See my answer below.
          – L. Holanda
          Nov 20 '15 at 22:35















        up vote
        257
        down vote



        accepted










        matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:



        public static void main(String args) throws ParseException {
        Pattern p = Pattern.compile("\d\d\d");
        Matcher m = p.matcher("a123b");
        System.out.println(m.find());
        System.out.println(m.matches());

        p = Pattern.compile("^\d\d\d$");
        m = p.matcher("123");
        System.out.println(m.find());
        System.out.println(m.matches());
        }

        /* output:
        true
        false
        true
        true
        */


        123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.






        share|improve this answer



















        • 16




          This answer is misleading. matchers() is not simply a find() with implied surrounding ^ and $. Be aware that calling .find() more than once may have different results if not preceeded by reset(), while matches() will always return same result. See my answer below.
          – L. Holanda
          Nov 20 '15 at 22:35













        up vote
        257
        down vote



        accepted







        up vote
        257
        down vote



        accepted






        matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:



        public static void main(String args) throws ParseException {
        Pattern p = Pattern.compile("\d\d\d");
        Matcher m = p.matcher("a123b");
        System.out.println(m.find());
        System.out.println(m.matches());

        p = Pattern.compile("^\d\d\d$");
        m = p.matcher("123");
        System.out.println(m.find());
        System.out.println(m.matches());
        }

        /* output:
        true
        false
        true
        true
        */


        123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.






        share|improve this answer














        matches tries to match the expression against the entire string and implicitly add a ^ at the start and $ at the end of your pattern, meaning it will not look for a substring. Hence the output of this code:



        public static void main(String args) throws ParseException {
        Pattern p = Pattern.compile("\d\d\d");
        Matcher m = p.matcher("a123b");
        System.out.println(m.find());
        System.out.println(m.matches());

        p = Pattern.compile("^\d\d\d$");
        m = p.matcher("123");
        System.out.println(m.find());
        System.out.println(m.matches());
        }

        /* output:
        true
        false
        true
        true
        */


        123 is a substring of a123b so the find() method outputs true. matches() only 'sees' a123b which is not the same as 123 and thus outputs false.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jul 26 '13 at 14:48









        Jonathan

        50731027




        50731027










        answered Dec 15 '10 at 13:04









        Sanjay T. Sharma

        19.3k34764




        19.3k34764








        • 16




          This answer is misleading. matchers() is not simply a find() with implied surrounding ^ and $. Be aware that calling .find() more than once may have different results if not preceeded by reset(), while matches() will always return same result. See my answer below.
          – L. Holanda
          Nov 20 '15 at 22:35














        • 16




          This answer is misleading. matchers() is not simply a find() with implied surrounding ^ and $. Be aware that calling .find() more than once may have different results if not preceeded by reset(), while matches() will always return same result. See my answer below.
          – L. Holanda
          Nov 20 '15 at 22:35








        16




        16




        This answer is misleading. matchers() is not simply a find() with implied surrounding ^ and $. Be aware that calling .find() more than once may have different results if not preceeded by reset(), while matches() will always return same result. See my answer below.
        – L. Holanda
        Nov 20 '15 at 22:35




        This answer is misleading. matchers() is not simply a find() with implied surrounding ^ and $. Be aware that calling .find() more than once may have different results if not preceeded by reset(), while matches() will always return same result. See my answer below.
        – L. Holanda
        Nov 20 '15 at 22:35












        up vote
        65
        down vote













        matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.






        share|improve this answer

















        • 32




          You could say that matches(p) is the same as find("^" + p + "$") if that's any clearer.
          – jensgram
          Dec 15 '10 at 12:56






        • 3




          Just an example to clarify the answer: "[a-z]+" with string "123abc123" will fail using matches() but will succeed using find().
          – bezmax
          Dec 15 '10 at 12:57






        • 3




          @Max Exactly, "123abc123".matches("[a-z]+") will fail just as "123abc123".find("^[a-z]+$") would. My point was, that matches() goes for a complete match, just as find() with both start and end anchors.
          – jensgram
          Dec 15 '10 at 12:59








        • 4




          Pattern.compile("some pattern").matcher(str).matches() is equal to Pattern.compile("^some pattern$").matcher(str).find()
          – AlexR
          Dec 15 '10 at 13:09






        • 2




          @AlexR / @jensgram: ...("some pattern").matcher(str).matches() is not exactly equal to ...("^some pattern$").matcher(str).find() that's only true in the first call. See my answer below.
          – L. Holanda
          Aug 11 '16 at 17:55

















        up vote
        65
        down vote













        matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.






        share|improve this answer

















        • 32




          You could say that matches(p) is the same as find("^" + p + "$") if that's any clearer.
          – jensgram
          Dec 15 '10 at 12:56






        • 3




          Just an example to clarify the answer: "[a-z]+" with string "123abc123" will fail using matches() but will succeed using find().
          – bezmax
          Dec 15 '10 at 12:57






        • 3




          @Max Exactly, "123abc123".matches("[a-z]+") will fail just as "123abc123".find("^[a-z]+$") would. My point was, that matches() goes for a complete match, just as find() with both start and end anchors.
          – jensgram
          Dec 15 '10 at 12:59








        • 4




          Pattern.compile("some pattern").matcher(str).matches() is equal to Pattern.compile("^some pattern$").matcher(str).find()
          – AlexR
          Dec 15 '10 at 13:09






        • 2




          @AlexR / @jensgram: ...("some pattern").matcher(str).matches() is not exactly equal to ...("^some pattern$").matcher(str).find() that's only true in the first call. See my answer below.
          – L. Holanda
          Aug 11 '16 at 17:55















        up vote
        65
        down vote










        up vote
        65
        down vote









        matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.






        share|improve this answer












        matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 15 '10 at 12:53









        khachik

        20.7k54280




        20.7k54280








        • 32




          You could say that matches(p) is the same as find("^" + p + "$") if that's any clearer.
          – jensgram
          Dec 15 '10 at 12:56






        • 3




          Just an example to clarify the answer: "[a-z]+" with string "123abc123" will fail using matches() but will succeed using find().
          – bezmax
          Dec 15 '10 at 12:57






        • 3




          @Max Exactly, "123abc123".matches("[a-z]+") will fail just as "123abc123".find("^[a-z]+$") would. My point was, that matches() goes for a complete match, just as find() with both start and end anchors.
          – jensgram
          Dec 15 '10 at 12:59








        • 4




          Pattern.compile("some pattern").matcher(str).matches() is equal to Pattern.compile("^some pattern$").matcher(str).find()
          – AlexR
          Dec 15 '10 at 13:09






        • 2




          @AlexR / @jensgram: ...("some pattern").matcher(str).matches() is not exactly equal to ...("^some pattern$").matcher(str).find() that's only true in the first call. See my answer below.
          – L. Holanda
          Aug 11 '16 at 17:55
















        • 32




          You could say that matches(p) is the same as find("^" + p + "$") if that's any clearer.
          – jensgram
          Dec 15 '10 at 12:56






        • 3




          Just an example to clarify the answer: "[a-z]+" with string "123abc123" will fail using matches() but will succeed using find().
          – bezmax
          Dec 15 '10 at 12:57






        • 3




          @Max Exactly, "123abc123".matches("[a-z]+") will fail just as "123abc123".find("^[a-z]+$") would. My point was, that matches() goes for a complete match, just as find() with both start and end anchors.
          – jensgram
          Dec 15 '10 at 12:59








        • 4




          Pattern.compile("some pattern").matcher(str).matches() is equal to Pattern.compile("^some pattern$").matcher(str).find()
          – AlexR
          Dec 15 '10 at 13:09






        • 2




          @AlexR / @jensgram: ...("some pattern").matcher(str).matches() is not exactly equal to ...("^some pattern$").matcher(str).find() that's only true in the first call. See my answer below.
          – L. Holanda
          Aug 11 '16 at 17:55










        32




        32




        You could say that matches(p) is the same as find("^" + p + "$") if that's any clearer.
        – jensgram
        Dec 15 '10 at 12:56




        You could say that matches(p) is the same as find("^" + p + "$") if that's any clearer.
        – jensgram
        Dec 15 '10 at 12:56




        3




        3




        Just an example to clarify the answer: "[a-z]+" with string "123abc123" will fail using matches() but will succeed using find().
        – bezmax
        Dec 15 '10 at 12:57




        Just an example to clarify the answer: "[a-z]+" with string "123abc123" will fail using matches() but will succeed using find().
        – bezmax
        Dec 15 '10 at 12:57




        3




        3




        @Max Exactly, "123abc123".matches("[a-z]+") will fail just as "123abc123".find("^[a-z]+$") would. My point was, that matches() goes for a complete match, just as find() with both start and end anchors.
        – jensgram
        Dec 15 '10 at 12:59






        @Max Exactly, "123abc123".matches("[a-z]+") will fail just as "123abc123".find("^[a-z]+$") would. My point was, that matches() goes for a complete match, just as find() with both start and end anchors.
        – jensgram
        Dec 15 '10 at 12:59






        4




        4




        Pattern.compile("some pattern").matcher(str).matches() is equal to Pattern.compile("^some pattern$").matcher(str).find()
        – AlexR
        Dec 15 '10 at 13:09




        Pattern.compile("some pattern").matcher(str).matches() is equal to Pattern.compile("^some pattern$").matcher(str).find()
        – AlexR
        Dec 15 '10 at 13:09




        2




        2




        @AlexR / @jensgram: ...("some pattern").matcher(str).matches() is not exactly equal to ...("^some pattern$").matcher(str).find() that's only true in the first call. See my answer below.
        – L. Holanda
        Aug 11 '16 at 17:55






        @AlexR / @jensgram: ...("some pattern").matcher(str).matches() is not exactly equal to ...("^some pattern$").matcher(str).find() that's only true in the first call. See my answer below.
        – L. Holanda
        Aug 11 '16 at 17:55












        up vote
        41
        down vote













        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.






        share|improve this answer

























          up vote
          41
          down vote













          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.






          share|improve this answer























            up vote
            41
            down vote










            up vote
            41
            down vote









            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.






            share|improve this answer












            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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 23 '13 at 18:00









            L. Holanda

            2,2262034




            2,2262034






















                up vote
                3
                down vote













                find() will consider the sub-string against the regular expression where as matches() will consider complete expression.



                find() will returns true only if the sub-string of the expression matches the pattern.



                public static void main(String args) {
                Pattern p = Pattern.compile("\d");
                String candidate = "Java123";
                Matcher m = p.matcher(candidate);

                if (m != null){
                System.out.println(m.find());//true
                System.out.println(m.matches());//false
                }
                }





                share|improve this answer



























                  up vote
                  3
                  down vote













                  find() will consider the sub-string against the regular expression where as matches() will consider complete expression.



                  find() will returns true only if the sub-string of the expression matches the pattern.



                  public static void main(String args) {
                  Pattern p = Pattern.compile("\d");
                  String candidate = "Java123";
                  Matcher m = p.matcher(candidate);

                  if (m != null){
                  System.out.println(m.find());//true
                  System.out.println(m.matches());//false
                  }
                  }





                  share|improve this answer

























                    up vote
                    3
                    down vote










                    up vote
                    3
                    down vote









                    find() will consider the sub-string against the regular expression where as matches() will consider complete expression.



                    find() will returns true only if the sub-string of the expression matches the pattern.



                    public static void main(String args) {
                    Pattern p = Pattern.compile("\d");
                    String candidate = "Java123";
                    Matcher m = p.matcher(candidate);

                    if (m != null){
                    System.out.println(m.find());//true
                    System.out.println(m.matches());//false
                    }
                    }





                    share|improve this answer














                    find() will consider the sub-string against the regular expression where as matches() will consider complete expression.



                    find() will returns true only if the sub-string of the expression matches the pattern.



                    public static void main(String args) {
                    Pattern p = Pattern.compile("\d");
                    String candidate = "Java123";
                    Matcher m = p.matcher(candidate);

                    if (m != null){
                    System.out.println(m.find());//true
                    System.out.println(m.matches());//false
                    }
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 10 '17 at 9:39









                    Jaap

                    54.6k20116129




                    54.6k20116129










                    answered Feb 10 '17 at 9:21









                    Sumanth Varada

                    22147




                    22147






















                        up vote
                        2
                        down vote













                        matches(); does not buffer, but find() buffers. find() searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.



                        That is why when you have a code like



                        1:Pattern.compile("[a-z]");

                        2:Pattern.matcher("0a1b1c3d4");

                        3:int count = 0;

                        4:while(matcher.find()){

                        5:count++: }


                        At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character] to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.






                        share|improve this answer

























                          up vote
                          2
                          down vote













                          matches(); does not buffer, but find() buffers. find() searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.



                          That is why when you have a code like



                          1:Pattern.compile("[a-z]");

                          2:Pattern.matcher("0a1b1c3d4");

                          3:int count = 0;

                          4:while(matcher.find()){

                          5:count++: }


                          At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character] to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.






                          share|improve this answer























                            up vote
                            2
                            down vote










                            up vote
                            2
                            down vote









                            matches(); does not buffer, but find() buffers. find() searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.



                            That is why when you have a code like



                            1:Pattern.compile("[a-z]");

                            2:Pattern.matcher("0a1b1c3d4");

                            3:int count = 0;

                            4:while(matcher.find()){

                            5:count++: }


                            At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character] to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.






                            share|improve this answer












                            matches(); does not buffer, but find() buffers. find() searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.



                            That is why when you have a code like



                            1:Pattern.compile("[a-z]");

                            2:Pattern.matcher("0a1b1c3d4");

                            3:int count = 0;

                            4:while(matcher.find()){

                            5:count++: }


                            At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character] to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 15 '16 at 21:36







                            user5767743





































                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4450045%2fdifference-between-matches-and-find-in-java-regex%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Full-time equivalent

                                さくらももこ

                                13 indicted, 8 arrested in Calif. drug cartel investigation