📜  Java中的 Matcher toString() 方法及示例

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

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

Matcher 类toString()方法用于获取此匹配器的字符串表示形式。此方法派生自 Object Class,其行为方式类似。

句法:

public String toString()

参数:此方法不带参数。

返回值:此方法返回一个字符串值,该值是此匹配器的字符串表示形式。

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

示例 1:

// Java code to illustrate toString() 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
            = " Geeks for For Geeks Geek";
  
        // Create a matcher for the input String
        Matcher matcher
            = pattern.matcher(stringToBeMatched);
  
        // Get the String representation of this matcher
        // using toString() method
        System.out.println(matcher.toString());
    }
}
输出:
java.util.regex.Matcher[pattern=(Geeks) region=0,25 lastmatch=]

示例 2:

// Java code to illustrate toString() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the regex to be checked
        String regex = "(GFG)";
  
        // Create a pattern from regex
        Pattern pattern
            = Pattern.compile(regex);
  
        // Get the String to be matched
        String stringToBeMatched
            = "FGF GFG GFG FGF";
  
        // Create a matcher for the input String
        Matcher matcher
            = pattern.matcher(stringToBeMatched);
  
        // Get the String representation of this matcher
        // using toString() method
        System.out.println(matcher.toString());
    }
}
输出:
java.util.regex.Matcher[pattern=(GFG) region=0,15 lastmatch=]

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