天天看點

正規表達式 學習筆記4.3

下面看看逆序環視結構:

public class GeneralSix {

public static void main(String[] args) {

String[] strings = new String[]{"see","bee","tee"};     

String[] regexs = new String[]{"(?<=s)ee","(?<!s)ee"};

for(String regex:regexs){

for(String str:strings){

Pattern p = Pattern.compile(regex);

Matcher m = p.matcher(str);

if(m.find()){

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

}else{

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

}

System.out.println("");

運作結果:

"see" 能夠比對正則:(?<=s)ee

"bee" 不能夠比對正則:(?<=s)ee

"tee" 不能夠比對正則:(?<=s)ee

"see" 不能夠比對正則:(?<!s)ee

"bee" 能夠比對正則:(?<!s)ee

"tee" 能夠比對正則:(?<!s)ee

(?<=s)ee

肯定逆序環視結構,用來查找前面為s的ee。

(?<!s)ee

否定逆序環視結構,用來查找之前不為s的ee

環視的注意事項:

l 環式結構僅用于布爾判斷,結構内的子表達式所比對的文本,不會儲存在整個表達式的比對結果中

l 逆序環視結構對子表達式存在限制

逆序環視結構的限制

l Perl,Python:逆序環視結構中的子表達式必須為固定長度

就是不能使用任何量詞,也不能使用多選分支,長度不相同的多選結構

l PHP,Java:逆序環視結構中的子表達式可以不定長度,但必須由上限

就是不能使用 *、+ 這樣的量詞。

l .NET:逆序環視結構中的子表達式完全沒有限制

從這個意義上說,.NET的正規表達式是做的最好的。

環視應用執行個體:

l 修整數值

l 要求:在數值中的合适位置插入逗号,将其修整為便于閱讀的形式

l 舉例:

·1234567890->1,234,567,890

·123456->123,456

l 需要插入逗号的位置:

·左側至少出現一位數字,右側出現的數字位數是3的倍數

l 正規表達式:

·(?=\d)(?=(\d{3}+))

public class GeneralSeven {

String[] numbers = new String[]{"123456","1234567890"};     

String regex = "(?<=\\d)(?=(\\d{3})+)";

for(String number:numbers){

System.out.println("替換前:"+number);

System.out.println("替換後:"+number.replaceAll(regex, ","));

替換前:123456

替換後:1,2,3,456

替換前:1234567890

替換後:1,2,3,4,5,6,7,890

這個結果有問題,123456應該顯示為,123,456

1234567890 應該為:1,234,567,890

問題出在:

 "(?<=\\d)(?=(\\d{3})+)";

右邊出現的是3的倍數,對這個字元串長度,就是比對到哪個為止,我們并沒有限定。

對肯定順序環結構對字元串的比對加以更準确的限制。

應該再添加一個否定循環結構:

String regex = "(?<=\\d)(?=(\\d{3})+(?!\\d))";

替換後:123,456

替換後:1,234,567,890

小結:

l 錨點:規定比對的位置

· \b、^、$、\A、\Z

l 環視:以子表達式對位置進行判斷

·(?=)、(?!)

·(?<)、(?<!)

·環視隻能進行布爾判斷

·逆序環視的限制

正規表達式 學習筆記4 完!

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