Javaregex 简明教程
Java Regex - Capturing Groups
捕获组是一种将多个字符视为单个单位的方法。它们是通过将待分组的字符置于一组圆括号内创建的。例如,正则表达式 (dog) 创建单个组,其中包含字母“d”、“o”和“g”。
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".
捕获组通过从左到右计算其左括号进行编号。例如,在表达式 A)(B© 中,存在四个这样的组 -
Capturing groups are numbered by counting their opening parentheses from the left to the right. In the expression A)(B©, for example, there are four such groups −
-
A)(B©
-
(A)
-
(B©)
-
©
若要找出表达式中有多少组,请对匹配器对象调用 groupCount 方法。groupCount 方法返回一个 int,显示匹配器模式中存在的分组数。
To find out how many groups are present in the expression, call the groupCount method on a matcher object. The groupCount method returns an int showing the number of capturing groups present in the matcher’s pattern.
还有一个特殊的组,组 0,它始终代表整个表达式。此组不包括在 groupCount 报告的总数中。
There is also a special group, group 0, which always represents the entire expression. This group is not included in the total reported by groupCount.
Example
以下示例说明如何从给定的字母数字字符串中找到数字字符串 -
Following example illustrates how to find a digit string from the given alphanumeric string −
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");
}
}
}
这会产生以下结果 −
This will produce the following result −