📜  Java中的 Matcher start() 方法及示例

📅  最后修改于: 2022-05-13 01:54:30.538000             🧑  作者: Mango

Java中的 Matcher start() 方法及示例

Matcher 类start()方法用于获取已经完成的匹配结果的起始索引。

句法:

public int start()

参数:此方法不带任何参数。

返回值:该方法返回匹配的第一个字符的索引。0

异常:如果尚未尝试匹配,或者之前的匹配操作失败,则此方法抛出IllegalStateException

下面的示例说明了 Matcher.start() 方法:

示例 1:

// Java code to illustrate start() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the regex to be checked
        String regex = "(G*k)";
  
        // Create a pattern from regex
        Pattern pattern
            = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched = "Geeks";
  
        // Create a matcher for the input String
        Matcher matcher
            = pattern
                  .matcher(stringToBeMatched);
  
        // Get the current matcher state
        MatchResult result
            = matcher.toMatchResult();
        System.out.println("Current Matcher: "
                           + result);
  
        while (matcher.find()) {
            // Get the first index of match result
            System.out.println(matcher.start());
        }
    }
}
输出:

示例 2:

// Java code to illustrate start() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the regex to be checked
        String regex = "(G*G)";
  
        // Create a pattern from regex
        Pattern pattern
            = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched = "GFG";
  
        // Create a matcher for the input String
        Matcher matcher
            = pattern
                  .matcher(stringToBeMatched);
  
        // Get the current matcher state
        MatchResult result
            = matcher.toMatchResult();
        System.out.println("Current Matcher: "
                           + result);
  
        while (matcher.find()) {
            // Get the first index of match result
            System.out.println(matcher.start());
        }
    }
}
输出:

参考: Oracle 文档