📌  相关文章
📜  Java中的 Matcher start(String) 方法及示例

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

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

Matcher 类start(String 字符串)方法用于从指定的字符串获取已经完成的匹配结果的开始索引。

句法:

public int start(String string)

参数:此方法采用参数字符串,该字符串是需要匹配模式的起始索引的字符串。

返回值:该方法返回从指定字符串匹配的第一个字符的索引

异常:此方法抛出:

  • 如果尚未尝试匹配,或者之前的匹配操作失败,则IllegalStateException
  • 如果模式中没有具有给定名称的捕获组,则出现IndexOutOfBoundsException

下面的示例说明了 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 = "\\b(?[A-Za-z\\s]+)";
  
        // Create a pattern from regex
        Pattern pattern
            = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched
            = "GeeksForGeeks";
  
        // 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("Geeks"));
        }
    }
}
输出:

示例 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 = "\\b(?[A-Za-z\\s]+)";
  
        // Create a pattern from regex
        Pattern pattern
            = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched
            = "   GFGFGFGFGFGFGFGFGFG";
  
        // 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("GFG"));
        }
    }
}
输出:

参考: Oracle 文档