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

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

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

Matcher 类group(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(?[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"));
        }
    }
}
输出:

示例 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(?[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"));
        }
    }
}
输出:

参考: Oracle 文档