Why does Java regex “matches” vs “find” get a different match when using non-greedy pattern?

后端 未结 2 1341
终归单人心
终归单人心 2021-01-12 23:03

So I ran into a bug caused by expecting the matches() method to find exactly the same match as using find(). Normally this is the case, but it appears that if a non-greedy p

相关标签:
2条回答
  • 2021-01-12 23:18

    This makes perfect sense.

    The matches(...) method must attempt to consume the whole string, so it does, even with a non-greedy pattern.

    The find(...) method may find a substring, so it stops at the point if finds any matching substring.

    0 讨论(0)
  • 2021-01-12 23:26

    They are supposed to be different. Matcher#matches attempts to match the complete input string using the implicit anchors ^ and $ around your regex, whereas Matcher#find matches whatever your regex can match.

    As per Javadoc:

    public boolean matches()

    Attempts to match the entire region against the pattern. If the match succeeds then more information can be obtained via the start, end, and group methods.

    and

    public boolean find()

    Attempts to find the next subsequence of the input sequence that matches the pattern.

    0 讨论(0)
提交回复
热议问题