Java中Matcher toMatchResult()方法的示例
java.util.regex.Matcher类表示执行各种匹配操作的引擎。该类没有构造函数,可以使用matches()
类java.util.regex.Pattern的方法创建/获取该类的对象。
此(匹配器)的toMatchResult()方法返回当前匹配器的匹配状态。
例子1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ToMatchResultExample { public static void main(String[] args) { String str = "<p>This <b>is</b> an <b>example</b>.</p>"; //正则表达式以匹配粗体标签的内容 String regex = "<b>(\\S+)</b>"; //创建一个模式对象 Pattern pattern = Pattern.compile(regex); //匹配字符串中的已编译模式 System.out.println("State of the matcher: "); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println(matcher.toMatchResult()); String result = matcher.group(1); } matcher = matcher.reset("<p>this is another <b>line</b>.</p>"); matcher.find(); System.out.println(""); System.out.println("State of the matcher after resetting it: \n"+matcher.toMatchResult()); } }
输出结果
State of the matcher: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,40 lastmatch=<b>is</b>] java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,40 lastmatch=<b>example</b>] State of the matcher after resetting it: java.util.regex.Matcher[pattern=<b>(\S+)</b> region=0,35 lastmatch=<b>line</b>]
例子2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ToMatchResultExample { public static void main(String[] args) { String regex = "[#]"; System.out.println("Enter a string: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //创建一个模式对象 Pattern pattern = Pattern.compile(regex); //创建一个Matcher对象 Matcher matcher = pattern.matcher(input); System.out.println("Match state: "); //找到比赛 while(matcher.find()) { System.out.println(matcher.toMatchResult()); } } }
输出结果
Enter a string: #This #is #a #sample #text Match state: java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#] java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#] java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#] java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#] java.util.regex.Matcher[pattern=[#] region=0,26 lastmatch=#]