📜  Java中的 MatchResult start() 方法和示例

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

Java中的 MatchResult start() 方法和示例

MatchResult 接口start()方法用于获取已经完成的匹配结果的开始索引。

句法:

public int start()

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

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

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

下面的示例说明了 MatchResult.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
        MatchResult matcher
            = pattern
                  .matcher(stringToBeMatched);
  
        while (((Matcher)matcher).find()) {
            // Get the first index of match result
            System.out.println(matcher.start());
        }
    }
}
输出:
3

示例 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
        MatchResult matcher
            = pattern
                  .matcher(stringToBeMatched);
  
        while (((Matcher)matcher).find()) {
            // Get the first index of match result
            System.out.println(matcher.start());
        }
    }
}
输出:
0
2

=