Regular Expression find method

前端 未结 2 1938
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 22:25

This is my code to find \"ab\" pattern in given string.

import java.util.regex.*;
public class RegExp
{
    public static void main(String[] arg         


        
相关标签:
2条回答
  • 2021-01-14 23:22

    As you can read in the documentation of find():

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

    This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

    If the match succeeds then more information can be obtained via the start, end, and group methods.

    So when you call matcher(String text) the first time nothing happens. It is only when you call find(), that it aims to find the first match. If you call find() a second time, it will aim to find the next match and so on.

    The following sequence diagram describes what happens:

    The matcher is constructed and each time find() is called the "cursor" is moved to the next match.

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

    The find method scans the input sequence looking for the next subsequence that matches the pattern and returns a boolean indicating the success of failure.

    Internally find method calls the search method (access control default) so that initiates a search to find a Pattern within the given bounds. At each match the bound will be incremented until all the matches were found.

    Behind the Matcher class it's a state machine that will hold the state of the match.

    On the other hand start method returns the start index as int of the subsequence captured by the latest match.

    If you want really go deeper I suggest to review the source code of Matcher class.

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