当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Matcher group(String)用法及代码示例


Matcher Class的group(String string)方法用于从指定的字符串获取已经完成的匹配结果的组。

用法:

public String group(String string)

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


返回值:此方法从指定的字符串返回匹配组的组。

异常:该方法抛出:

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

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

示例1:

// Java code to illustrate end() method 
  
import java.util.regex.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the regex to be checked 
        String regex = "\\b(?<Geeks>[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 group matched using group() method 
            System.out.println(matcher.group("Geeks")); 
        } 
    } 
}
输出:

Current Matcher: java.util.regex.Matcher[pattern=\b(?[A-Za-z\s]+) region=0,13 lastmatch=]
GeeksForGeeks

示例2:

// Java code to illustrate end() method 
  
import java.util.regex.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
       // Get the regex to be checked 
        String regex = "\\b(?<GFG>[A-Za-z\\s]+)"; 
  
        // Create a pattern from regex 
        Pattern pattern 
            = Pattern.compile(regex); 
  
        // Get the String to be matched 
        String stringToBeMatched 
            = "GFG FGF 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 group matched using group() method 
            System.out.println(matcher.group("GFG")); 
        } 
    } 
}
输出:

Current Matcher: java.util.regex.Matcher[pattern=\b(?[A-Za-z\s]+) region=0,11 lastmatch=]
GFG FGF GFG

参考: Oracle Doc



相关用法


注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 Matcher group(String) method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。