我正在从这个网站学习Java正则表达式:http://www.tutorialspoint.com/java/java_regular_expressions.htm
我正在努力为该页面上的大多数示例/输入解决方案提供读取输出。 m.group(0)是指(。*)还是m.group(1)指(+ d +)等?
例如: 输入:
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 QT300
Found value: 0
除了开始和结束方法之外,对于这个,我不确定.start,.end正在做什么:
输入:
public class RegexMatches
{
private static final String REGEX = "\\bcat\\b";
private static final String INPUT =
"cat cat cat cattie cat";
public static void main( String args[] ){
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;
while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}
}
输出:
match number 1
start(): 0
end(): 3
match number 2
start(): 4
end(): 7
match number 3
start(): 8
end(): 11
match number 4
start(): 19
end(): 22
答案 0 :(得分:2)
阅读Matcher.group(int group)
的javadoc:
捕获组从左到右编制索引,从1开始。组零表示整个模式,因此表达式m.group(0)等同于m.group()。
所以,你拥有的是:
(.*)(\\d+)(.*)
^^^^^^^^^^^^^^ group 0
^^^^ group 1
^^^^^^ group 2
^^^^ group 3