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

后端 未结 5 2026
感情败类
感情败类 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:15

    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.

提交回复
热议问题