Java 正则表达式捕获组
我正在尝试理解此代码块。在第一个中,我们在表达式中寻找的是什么?
我的理解是,它是任何字符(0或更多次*),后跟0到9之间的任何数字(一次或多次+),然后是任何字符(0次或多次*)。
执行此命令时,结果为:
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0
有人可以和我一起经历这个吗?
使用捕获组有什么好处?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTut3 {
public static void main(String args[]) {
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");
}
}
}