我无法理解组的输出,它是如何考虑模式中的每个paranthesis并将其与变量'line'等同于此处。请解释
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");
}
}
}
答案 0 :(得分:-1)
模式"(.*)(\\d+)(.*)"
表示:
(.*) - Consume anything and store it in group 0
(\\d+) - Consume a number and store it in the next group, i.e. group 2
(.*) - Consume anything and store it in the next group
通过这种方式,模式将在字符串中找到一个数字,并将其中的所有内容存储在组0
中,组1
中的数字以及组2
中其余字符串的数字
答案 1 :(得分:-1)
m.group(0)始终匹配整个模式。你的比赛实际上从1开始,而不是0。
m.group(0): matches the whole pattern
m.group(1): first parenthesis
m.group(2): second set of parenthesis
m.group(3): third set
编辑:纠正