Java 編程 正則表達式

正則表達式:搜索、編輯和操作字符,模式會從左到右匹配文本。

編寫規則:

常見匹配符號:

  • . 匹配所有單個字符,除了換行符號
  • ^regex 匹配的字符的開頭必須是regex
  • regex$ 匹配的字符的結尾必須是regex
  • [abc]    複選集定義,匹配字母爲 a或者b或者c
  • [^abc] 當^ 在中括號中以第一個字符開始,則表示否定模式,此匹配除了a或b或c的所有的字符。
  • [a-d1-7] 匹配a到d 的字符和1到7的數字。
  • X|Z 匹配 X或者Z

元字符:一個預定義的字符

  • \d    匹配一個數字,等價於 [0-9]
  • \D    匹配一個非數字,等價於 [^0-9]
  • \s     匹配一個空格 等價於[\t\n\x0b\r\f] 的縮寫
  • \S    匹配一個非空格
  • \w    匹配一個單詞符號,包括大小寫,數字,下劃線,等價於 [a-zA-Z_0-9]
  • \W   匹配一個非單詞字符,除包括大小寫,數字,下劃線之外,等同於[^\w]

限定符號:定義一個元素可以發送的頻率

  • *         匹配>= 0個,等價於{0,}
  • +        匹配>= 1個,等價於{1,}
  • ?        匹配0個或者1個,等價於{0,1}
  • {X}     只匹配X個字符,\d{3}匹配3個數字, {10}表示匹配任何長度使10得字符串
  • {X,Y}  匹配>=X 且 <= Y 個,\d{1,4} 表示匹配至少一個最多4個數字
  • *?      如果 ? 是限定符 * 或 + 或 ? 或 {} 後面的第一個字符,那麼表示非貪婪模式(儘可能少的匹配字符而不是默認的貪婪模式

分組和反向引用:

// 去除單詞與 , 和 . 之間的空格
        String Str = "Hello , World .";
        String pattern = "(\\w)(\\s+)([.,])";
        // $0 匹配 `(\w)(\s+)([.,])` 結果爲 `o空格,` 和 `d空格.`
        // $1 匹配 `(\w)` 結果爲 `o` 和 `d`
        // $2 匹配 `(\s+)` 結果爲 `空格` 和 `空格`
        // $3 匹配 `([.,])` 結果爲 `,` 和 `.`
        // 我們使用了 [.] 來匹配普通字符 . 而不需要使用 [\\.]。因爲正則對於 []
        // 中的 .,會自動處理爲 [\.],即普通字符 . 進行匹配。
        System.out.println(Str.replaceAll(pattern, "$1$3")); // Hello, World.

小括號()可以達到對正則表達式進行分組的效果

反斜槓 \ 在 Java 中表示轉義字符,這意味着 被轉義的字符在 Java 擁有預定義的含義。

  • 在匹配 . 或 { 或 [ 或 ( 或 ? 或 $ 或 ^ 或 * 這些特殊字符時,需要在前面加上 \,比如匹配 . 時,但對於正則表達式來說就是 \.
  • 在匹配 \ 時,對於正則表達式來說就是 \\

內置字符串正則處理方法:

System.out.println("wjx".matches("wjx"));
String[] split = "x c f".split("\\s");
for (String s:split) {
       System.out.println(s);
}
System.out.println("------------");
System.out.println("x v f".replaceAll("\\s", "-"));

Java 模式匹配

java 中的正則表達式類,java.util.regex.Pattern 和 java.util.regex.Matcher

步驟如下:

  1. 通過正則表達式創建模式對象,Pattern
  2. 通過模式 Pattern ,根據指定字符串創建匹配對象 Matcher
  3. 通過匹配對象 Matcher, 根據正則表達式操作字符。
    public static void p3(){
        String text = "Hello Regex";
        Pattern pattern = Pattern.compile("\\w+");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()){
            System.out.println("start index " +matcher.start());
            System.out.println("end index " +matcher.end());
            System.out.println(matcher.group());
        }
    }

類使用詳解

捕獲組的概念:捕獲組可以通過從左到右計算其開括號來編號,編號是從1 開始的。例如,在表達式 ((A)(B(C)))中,存在四個這樣的組:

1        ((A)(B(C)))
2        (A)
3        (B(C))
4        (C)

組零始終代表整個表達式。

Pattern類用於創建一個正則表達式,也可以說創建一個匹配模式。但可以通過Pattern.complie(String regex)簡單工廠方法創建一個正則表達式。

Pattern p=Pattern.compile("\\w+"); 
p.pattern();//返回 \w+ 

1.Pattern.split(CharSequence input) 用於分隔字符串,並返回一個String[]

Pattern p=Pattern.compile("\\d+"); 
String[] str=p.split("我的QQ是:456456我的電話是:0532214我的郵箱是:[email protected]"); 

結果:str[0]="我的QQ是:" str[1]="我的電話是:" str[2]="我的郵箱是:[email protected]" 

2 Pattern.matcher(String regex,CharSequence input)是一個靜態方法,用於快速匹配字符串,該方法適合用於只匹配一次,且匹配全部字符串.

Pattern.matches("\\d+","2223");//返回true 
Pattern.matches("\\d+","2223aa");//返回false,需要匹配到所有字符串才能返回true,這裏aa不能匹配到 
Pattern.matches("\\d+","22bb23");//返回false,需要匹配到所有字符串才能返回true,這裏bb不能匹配到

3.Pattern.matcher(CharSequence input) Pattern.matcher(CharSequence input)返回一個Matcher對象.

Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.pattern();//返回p 也就是返回該Matcher對象是由哪個Pattern對象的創建的 

4.Matcher.matches()/ Matcher.lookingAt()/ Matcher.find()

三個方法均返回boolean類型,當匹配到時返回true,沒匹配到則返回false 

Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.matches();//返回false,因爲bb不能被\d+匹配,導致整個字符串匹配未成功. 
Matcher m2=p.matcher("2223"); 
m2.matches();//返回true,因爲\d+匹配到了整個字符串

lookingAt()對前面的字符串進行匹配,只有匹配到的字符串在最前面才返回true 

Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.lookingAt();//返回true,因爲\d+匹配到了前面的22 
Matcher m2=p.matcher("aa2223"); 
m2.lookingAt();//返回false,因爲\d+不能匹配前面的aa 

find()對字符串進行匹配,匹配到的字符串可以在任何位置. 

Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.find();//返回true 
Matcher m2=p.matcher("aa2223"); 
m2.find();//返回true 
Matcher m3=p.matcher("aa2223bb"); 
m3.find();//返回true 
Matcher m4=p.matcher("aabb"); 
m4.find();//返回false 

5.Mathcer.start()/ Matcher.end()/ Matcher.group()

start()返回匹配到的子字符串在字符串中的索引位置. 
end()返回匹配到的子字符串的最後一個字符在字符串中的索引位置. 
group()返回匹配到的子字符串 

Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("aaa2223bb"); 
m.find();//匹配2223 
m.start();//返回3 
m.end();//返回7,返回的是2223後的索引號 
m.group();//返回2223 

Mathcer m2=m.matcher("2223bb"); 
m.lookingAt();   //匹配2223 
m.start();   //返回0,由於lookingAt()只能匹配前面的字符串,所以當使用lookingAt()匹配時,start()方法總是返回0 
m.end();   //返回4 
m.group();   //返回2223 

Matcher m3=m.matcher("2223bb"); 
m.matches();   //匹配整個字符串 
m.start();   //返回0,原因相信大家也清楚了 
m.end();   //返回6,原因相信大家也清楚了,因爲matches()需要匹配所有字符串 
m.group();   //返回2223bb 

正則表達式的分組在java中是怎麼使用的,start(),end(),group()均有一個重載方法它們是start(int i),end(int i),group(int i)專用於分組操作,Mathcer類還有一個groupCount()用於返回有多少組. 

Pattern p=Pattern.compile("([a-z]+)(\\d+)"); 
Matcher m=p.matcher("aaa2223bb"); 
m.find();   //匹配aaa2223 
m.groupCount();   //返回2,因爲有2組 
m.start(1);   //返回0 返回第一組匹配到的子字符串在字符串中的索引號 
m.start(2);   //返回3 
m.end(1);   //返回3 返回第一組匹配到的子字符串的最後一個字符在字符串中的索引位置. 
m.end(2);   //返回7 
m.group(1);   //返回aaa,返回第一組匹配到的子字符串 
m.group(2);   //返回2223,返回第二組匹配到的子字符串 


Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("我的QQ是:456456 我的電話是:0532214 我的郵箱是:[email protected]"); 
while(m.find()) { 
     System.out.println(m.group()); 
} 
輸出:
456456 
0532214 
123 

如將以上while()循環替換成 
while(m.find()) { 
     System.out.println(m.group()); 
     System.out.print("start:"+m.start()); 
     System.out.println(" end:"+m.end()); 
} 
輸出:
456456 
start:6 end:12 
0532214 
start:19 end:26 
123 
start:36 end:39 

 

轉載文章

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章