量词的局限
l 量词只能规定之前字符或字符组的出现次数
l 如果要规定一个字符串的出现次数,必须使用括号(),在括号内填写字符串,在闭括号之后添加量词
例子:
public class GeneralThree {
public static void main(String[] args) {
String[] strs = new String[] { "ac", "acc", "accc", "acac","acacac"};
String regex = "ac+";
String regex2 = "(ac)+";
for (String string : strs) {
if(regexMatch(string,regex)){
System.out.println(string +"能够匹配正则:" + regex);
}else{
System.out.println(string +"不能够匹配正则:" + regex);
}
if(regexMatch(string,regex2)){
System.out.println(string +"能够匹配正则:" + regex2);
System.out.println(string +"不能够匹配正则:" + regex2);
private static boolean regexMatch(String s, String regex) {
return s.matches(regex);
运行结果:
ac能够匹配正则:ac+
acc能够匹配正则:ac+
accc能够匹配正则:ac+
acac不能够匹配正则:ac+
acacac不能够匹配正则:ac+
ac能够匹配正则:(ac)+
acc不能够匹配正则:(ac)+
accc不能够匹配正则:(ac)+
acac能够匹配正则:(ac)+
acacac能够匹配正则:(ac)+
括号的用途:多选结构
l 用途:表示某个位置可能出现的字符串
l 字符组只能表示某个位置可能出现的单个字符,而不能表示某个位置可能出现的字符串
l 形式:
·(...|...),在竖线两端添加各个字符串
·(...|...|...|...)
如果希望某个位置出现:this或者that,字符组对此事无能为力的,须采用多选结构。
public class GeneralFour {
String[] strs = new String[] { "this", "that", "thit"};
String regex = "th[ia][st]";
这是字符组的匹配结果:
this能够匹配正则:th[ia][st]
that能够匹配正则:th[ia][st]
thit能够匹配正则:th[ia][st]
连thit也匹配了,我们希望匹配this和that 这是因为第一个字符组[ia]和第二个字符组[st]没有建立联系。等于i去匹配[ia],t去匹配[st]的错误问题。
应该修改规则、使用多选结构:
String regex = "th(is|at)";
或者:String regex = "(this|that)";
this能够匹配正则:(this|that)
that能够匹配正则:(this|that)
thit不能够匹配正则:(this|that)
将共同部分提取到多选之外,能够提高正则表达式匹配的效率,但是,这个表达式的阅读者,并不见得很容易理解。实际开发的时候,应当根据具体情况来定。
推荐使用:String regex = "(this|that)";
括号的用途:捕获分组
l 作用:将括号内的字表达式捕获的字符串存放到匹配结果中,共匹配完成后访问
·使用普通的括号()
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GeneralFive {
String email = "[email protected]";
String regex = "(\\w+)@([\\d\\.\\w]+)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(email);
if(m.find()){
System.out.println("email address is:\t" + m.group(0));
System.out.println("username is:\t" + m.group(1));
System.out.println("hostname is:\t" + m.group(2));
email address is: [email protected]
username is: abacdemasterhappy
hostname is: 163.com
所有捕获分组,都是从编号为1开始,编号为0表示默认整个正则表达式所匹配的文本(它不能由捕获分组来加以修改的)。
未完待续。。。
本文转自jooben 51CTO博客,原文链接:http://blog.51cto.com/jooben/317568