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

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

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

Matcher 类regionStart()方法用于获取当前匹配器中模式要匹配的区域的 startIndex。此方法返回一个整数值,它是此匹配器区域的 startIndex。

句法:

public int regionStart()

参数:此方法不带参数。

返回值:此方法返回一个整数值,该值是此匹配器区域的 startIndex。

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

示例 1:

// Java code to illustrate regionStart() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the regex to be checked
        String regex = "(Geeks)";
  
        // Create a pattern from regex
        Pattern pattern
            = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched
            = "GeeksForGeeks Geeks for For Geeks Geek";
  
        // Create a matcher for the input String
        Matcher matcher
            = pattern.matcher(stringToBeMatched);
  
        // Get previous startIndex of region
        // using regionStart() method
        System.out.println("Before changing region, "
                           + " Region starts from: "
                           + matcher.regionStart());
  
        // Restrict the region to 2, 10
        matcher = matcher.region(2, 10);
  
        // Get previous startIndex of region
        // using regionStart() method
        System.out.println("After changing region, "
                           + " Region starts from: "
                           + matcher.regionStart());
    }
}
输出:
Before changing region,  Region starts from: 0
After changing region,  Region starts from: 2

示例 2:

// Java code to illustrate regionStart() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the regex to be checked
        String regex = "(F*F)";
  
        // Create a pattern from regex
        Pattern pattern
            = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched
            = "GFGFGFGFGFGFGFGFGFG FGF GFG GFG FGF";
  
        // Create a matcher for the input String
        Matcher matcher
            = pattern.matcher(stringToBeMatched);
  
        // Get previous startIndex of region
        // using regionStart() method
        System.out.println("Before changing region, "
                           + " Region starts from: "
                           + matcher.regionStart());
  
        // Restrict the region to 5, 10
        matcher = matcher.region(5, 10);
  
        // Get previous startIndex of region
        // using regionStart() method
        System.out.println("After changing region, "
                           + " Region starts from: "
                           + matcher.regionStart());
    }
}
输出:
Before changing region,  Region starts from: 0
After changing region,  Region starts from: 5

参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/regex/Matcher.html#regionStart–