捕获组是将多个角色视为一个单元的一种方法.它们是通过将要分组的字符放在一组括号中来创建的.例如,正则表达式(dog)创建一个包含字母"d","o"和"g"的组.
捕获组的编号通过计算它们的左括号来计算从左到右.在表达式((A)(B(C)))中,例如,有四个这样的组 :
(( A)(B(C)))
(A)
(B(C))
(C)
要查明表达式中存在多少个组,请在匹配器对象上调用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 to be scanned to find the pattern. String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. 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 QT300Found value: 0
免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除