通过将要分组的字符放在一组括号内来创建它们。例如,正则表达式(Dog)创建一个包含字母“ d”,“ o”和“ g”的单个组。
捕获组通过从左到右计数其左括号进行编号。例如,在表达式(A)(B(C)中,存在四个这样的组-
链接:https://www.learnfk.comhttps://www.learnfk.com/javaregex/javaregex-capturing-groups.html
来源:LearnFk无涯教程网
若要了解表达式中存在多少个组,请对Matcher对象调用groupCount方法。groupCount方法返回一个int,显示匹配器模式中存在的捕获组的数量。
还有一个特殊的组,组0,它始终表示整个表达式。此组不包括在groupCount报告的总数中。
以下示例说明如何从给定的字母数字字符串中查找数字字符串
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String args[] ) { //要扫描的字符串以查找模式。 String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; //创建Pattern对象 Pattern r = Pattern.compile(pattern); //创建匹配器对象。 Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); } else { System.out.println("NO MATCH"); } } }
这将产生以下输出-
Found value: This order was placed for QT3000! OK? Found value: This order was placed for QT300 Found value: 0
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)