如果你使用的是Java,那么你之前很有可能会看到其模式匹配。 String#matches(String)方法在内部使用Pattern类型,它包含更复杂的功能:
通过编译正则表达式来创建模式。 该模式与任何输入字符串匹配,并且可以选择查找捕获组,这些捕获组隔离了字符串数据的某些部分。
该API的用法如下:
Pattern pattern = Pattern.compile("([\\^\\S]+) is powerful");
Matcher matcher = pattern.matcher("Java is powerful");
System.out.println(matcher.find()); // true
System.out.println(matcher.group()); // Java is powerful
System.out.println(matcher.group(1)); // Java
find()方法查找模式的下一个匹配项,在此示例中与整个输入字符串匹配。 group()方法将返回整个捕获组,即匹配整个模式,或者在使用索引限定时返回单个捕获组。 捕获组索引从1开始,而不是从0开始。
还有matches()方法,其工作原理略有不同:
Pattern pattern = Pattern.compile("([\\^\\S]+) is powerful");
Matcher matcher = pattern.matcher("Our Java is powerful");
System.out.println(matcher.matches()); // false
System.out.println(matcher.find()); // true
matchs()尝试从头到尾将整个输入字符串与模式匹配,而find()仅尝试在输入字符串中的某处找到模式。
另外提醒一下:请仅对不重复重复的单个匹配调用使用快捷方式方法String#matches(String)或Pattern#matches(String,CharSequence)。 模式编译起来很繁琐,我们应该利用模式类型的不变性,并将其重用于多个匹配项。
发现帖子有用吗? 欢迎评论转发!
抽丝剥茧,细说架构那些事~
原文:https://blog.51cto.com/14634606/2461203