使用Matcher类,最重要的一个概念必须清楚:组(Group),在正则表达式中
()定义了一个组,由于一个正则表达式可以包含很多的组,所以下面先说说怎么划分组的,
以及这些组和组的下标怎么对应的.
下面我们看看一个小例子,来说明这个问题
引用\w(\d\d)(\w+)
这个正则表达式有三个组:
整个\w(\d\d)(\w+) 是第0组 group(0)
(\d\d)是第1组 group(1)
(\w+)是第2组 group(2)
我们看看和正则表达式匹配的一个字符串x99SuperJava,
group(0)永远都是匹配整个表达式的字符串的那部分x99SuperJava
group(1)是第1组(\d\d)匹配的部分:99
group(2)是第二组(\w+)匹配的那部分SuperJava
下面我们写一个程序来验证一下:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String regex = "\\w(\\d\\d)(\\w+)";
String candidate = "x99SuperJava";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(candidate);
if(matcher.find()){
int gc = matcher.groupCount();
for(int i = 0; i <= gc; i++)
System.out.println("group " + i + " :" + matcher.group(i));
}
}
}
运行结果:
group 0 :x99SuperJava
group 1 :99
group 2 :SuperJava
另外一个例子:
public class Test {
public static void main(String args[]){
test();
}
public static void test(){
//create a Pattern
Pattern p = Pattern.compile("B(ond)");
//create a Matcher and use the Matcher.group(int) method
String candidateString = "My name is Bond. James Bond.";
//create a helpful index for the sake of output
Matcher matcher = p.matcher(candidateString);
//Find group number 0 of the first find
matcher.find();
String group_0 = matcher.group(0);
String group_1 = matcher.group(1);
System.out.println("Group 0 " + group_0);
System.out.println("Group 1 " + group_1);
System.out.println(candidateString);
//Find group number 1 of the second find
matcher.find();
group_0 = matcher.group(0);
group_1 = matcher.group(1);
System.out.println("Group 0 " + group_0);
System.out.println("Group 1 " + group_1);
System.out.println(candidateString);
}
}
运行结果:
Group 0 Bond
Group 1 ond
My name is Bond. James Bond.
Group 0 Bond
Group 1 ond
My name is Bond. James Bond.
例子:
public class Test {
public static void main(String args[]){
StringBuffer sb = new StringBuffer();
String replacement = "Smith";
Pattern pattern = Pattern.compile("Bond");
Matcher matcher =pattern.matcher("My name is Bond. James Bond. I would like a martini.");
matcher.find();
matcher.appendReplacement(sb, replacement);// 结果是My name is Smith. James
// Smith
matcher.appendTail(sb);
System.out.println(sb);
}
}
运行结果: My name is Smith. James Bond. I would like a martini.