Java中的 Matcher pattern() 方法及示例
Matcher 类的pattern()方法用于获取该匹配器要匹配的模式。
句法:
public Pattern pattern()
参数:此方法不接受任何参数。
返回值:该方法返回一个Pattern ,这是该Matcher要匹配的模式。
下面的示例说明了 Matcher.pattern() 方法:
示例 1:
// Java code to illustrate pattern() 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";
// Create a matcher for the input String
Matcher matcher
= pattern.matcher(stringToBeMatched);
// Get the Pattern using pattern() method
System.out.println("Pattern: "
+ matcher.pattern());
}
}
输出:
Pattern: Geeks
示例 2:
// Java code to illustrate pattern() 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
= "GFGFGFGFGFGFGFGFGFG";
// Create a matcher for the input String
Matcher matcher
= pattern.matcher(stringToBeMatched);
// Get the Pattern using pattern() method
System.out.println("Pattern: "
+ matcher.pattern());
}
}
输出:
Pattern: GFG
参考: Oracle 文档