天天看點

正規表達式 學習筆記3.3

捕獲分組的注意事項:

l 隻要使用了括号,就存在捕獲分組

l 捕獲分組按照開括号出現的從左到右的順序編号,遇到括号嵌套的情況也是如此

l 如果捕獲分組之後存在量詞,則比對結果中,捕獲分組儲存的是子表達式最後一次比對的字元串

例子:

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class GeneralSix {

public static void main(String[] args) {

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("比對結果:\t" + m.group(0));

System.out.println("分組1:\t" + m.group(1));

System.out.println("分組2:\t" + m.group(2));

System.out.println("分組3:\t" + m.group(3));

}

運作結果:

比對結果: [email protected]

分組1: [email protected]

分組2: abacdemasterhappy

分組3: 163.com

隻是在正規表達式的兩端添加了一個( ),此時出現括号嵌套的情況。

依照括号從左到右的順序,發現,第一個括号對應整個正規表達式,第二個對應使用者名正規表達式,第三個括号用于比對主機名的正規表達式。

再看一個:

public class GeneralSeven {

String regex = "(\\w)+@([\\d\\.\\w])+";

分組1: y

分組2: m

将量詞作用整個捕獲分組。比對完成之後,捕獲分組所儲存的就是最後一次它所比對的文本。

[email protected]

相當于比對使用者名的最後一個字元。

捕獲分組的事項講解到此!

不捕獲文本的括号

l 如果正規表達式很複雜,或者需要處理的文本很長,捕獲分組會降低效率

l 作用:僅僅用來對表達式分組,而不把分組捕獲的文本存入結果

l 形式:

·(?:...)

注意:不捕獲文本的括号,并不是所有語言都有提供,為了增加可讀性,并不推薦使用“不捕獲文本的括号”。

public class GeneralEight {

String regex = "(?:abacdemasterhappy|admin)@(163.com)";

分組1: 163.com

括号的用途:反向引用

l 作用:在表達式的某一部分,動态重複之前子表達式所比對的文本

l 形式:\1

public class GeneralNine {

String[] strs = new String[] { "<h1>good,good</h1>", "<h1>bad</h2>"};

String regex = "<\\w+>[^<]+</\\w+>";

for (String string : strs) {

if(regexMatch(string,regex)){

System.out.println(string +"能夠比對正則:" + regex);

}else{

System.out.println(string +"不能夠比對正則:" + regex);

private static boolean regexMatch(String s, String regex) {

return s.matches(regex);

<h1>good,good</h1>能夠比對正則:<\w+>[^<]+</\w+>

<h1>bad</h2>能夠比對正則:<\w+>[^<]+</\w+>

未完待續。。。

本文轉自jooben 51CTO部落格,原文連結:http://blog.51cto.com/jooben/317569

繼續閱讀