1. 程式人生 > 實用技巧 >正則表示式的使用(Java)

正則表示式的使用(Java)

概述

本文主要介紹正則表示式的程式碼使用
學習正則表示式的基本語法,可以參考使用手冊:https://tool.oschina.net/uploads/apidocs/jquery/regexp.html

但是有幾個問題需要特別注意:

① 轉義符號 \ 的問題

比如,我們需要匹配一個數字,對應的正則表示式是:\d,因為在 Java 中正則表示式是通過字串的形式表示的,所以,在 Java 中對應的寫法為:"\\d"


正則表示式的作用

我認為,正則表示式的作用有兩個:

  • ① 匹配:判斷給定的字串是否符合格式,比如:郵箱地址匹配、密碼安全性驗證。
  • ② 捕獲:查詢給定文字,提取出固定格式的字串,比如:提取出文字中所有的電話號碼。

匹配的使用

匹配的使用比較簡單,具體程式碼如下:

//需要匹配的字串
String str = "abc";

//對應的正則表示式
String regexStr = "[a-z]{3}";

//使用如下程式碼進行匹配
Pattern p = Pattern.compile(regexStr);
Matcher m = p.matcher(str);
System.out.println(m.matchers());

更簡化的寫法:

System.out.println("abc".matches("[a-z]{3}"));

捕獲的使用

要理解捕獲,需要引入一個概念:

捕獲組: 給定一個正則表示式:((A)(B(C))),在進行正則表示式匹配查詢之後,會產生一個捕獲組,順序為:((A)(B(C))) (A) (B(C)) (C),分別對應編號:0 1 2 3。我們可以使用這個編號從捕獲組中得到對應的字串。

具體程式碼如下:

String str = "This order was placed for QT3000! OK?";
String regexStr = "(\\D*)(\\d+)(.*)";

Pattern p = Pattern.compile(regexStr);
Matcher m = p.matcher(str);
if (m.find( )) {
    System.out.println("Found value: " + m.group(0) );//This order was placed for QT3000! OK?
    System.out.println("Found value: " + m.group(1) );//This order was placed for QT
    System.out.println("Found value: " + m.group(2) );//3000
    System.out.println("Found value: " + m.group(3) ); //! OK?
} else {
    System.out.println("NO MATCH");
}

注意(pattern) (?:pattern) (?=pattern)等表示式是否會消耗字元,是否會產生捕獲,詳情可以看文件:https://tool.oschina.net/uploads/apidocs/jquery/regexp.html


Matcher 類

Matcher類有很多功能強大的 API,使用可以參考菜鳥教程:https://www.runoob.com/java/java-regular-expressions.html


參考

[1] 正則表示式使用手冊:https://tool.oschina.net/uploads/apidocs/jquery/regexp.html
[2] 菜鳥教程:https://www.runoob.com/java/java-regular-expressions.html
[3] 如何在 Java 中使用正則表示式:https://mp.weixin.qq.com/s/IcATjoRJrOhNQxy9ouderA