Java中的 Matcher toMatchResult() 方法及示例
Matcher 类的toMatchResult()方法用于获取此 Matcher 的当前结果状态。
句法:
public MatchResult toMatchResult()
参数:此方法不带任何参数。
返回值:该方法返回一个MatchResult与当前 Matcher 的匹配结果状态。
下面的示例说明了 Matcher.toMatchResult() 方法:
示例 1:
// Java code to illustrate toMatchResult() 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 result state
// using toMatchResult() method
System.out.println("Result: "
+ matcher.toMatchResult());
}
}
输出:
Result: java.util.regex.Matcher[pattern=Geeks region=0, 13 lastmatch=]
示例 2:
// Java code to illustrate toMatchResult() 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 result state
// using toMatchResult() method
System.out.println("Result: "
+ matcher.toMatchResult());
}
}
输出:
Result: java.util.regex.Matcher[pattern=GFG region=0, 19 lastmatch=]
参考: Oracle 文档