量詞的局限
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