java中的Regex

來源:互聯網
上載者:User

標籤:hone   regex   功能   abc   line   scanner   match   數字   分析   

java中的Regex:

1:常見的表示規則:

 1 \\      反斜線字元 (即:\) 2  3  4 字元類  5 [abc] a、b 或 c(簡單類)  6 [^abc] 任何字元,除了 a、b 或 c(否定)  7 [a-zA-Z] a 到 z 或 A 到 Z,兩頭的字母包括在內(範圍)  8 [a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](並集)  9 [a-z&&[def]] d、e 或 f(交集) 10 [a-z&&[^bc]] a 到 z,除了 b 和 c:[ad-z](減去) 11 [a-z&&[^m-p]] a 到 z,而非 m 到 p:[a-lq-z](減去) 12 13 預定義字元類 14 . 任何字元(與行結束符可能匹配也可能不匹配) 
\ 轉意字元 (\\表示:\,\\.表示:\.即:點本身)15 \d 數字:[0-9] 16 \D 非數字: [^0-9] 17 \s 空白字元:[ \t\n\x0B\f\r] 18 \S 非空白字元:[^\s] 19 \w 單詞字元:[a-zA-Z_0-9] 20 \W 非單詞字元:[^\w] 21 22 邊界匹配器 23 ^ 行的開頭 24 $ 行的結尾 25 \b 單詞邊界 26 \B 非單詞邊界 27 \A 輸入的開頭 28 \G 上一個匹配的結尾 29 \Z 輸入的結尾,僅用於最後的結束符(如果有的話) 30 \z 輸入的結尾 31 32 Greedy 數量詞 33 X? X,一次或一次也沒有 34 X* X,零次或多次 35 X+ X,一次或多次 36 X{n} X,恰好 n 次 37 X{n,} X,至少 n 次 38 X{n,m} X,至少 n 次,但是不超過 m 次

 

例子:1:判斷是否是手機號是否以13或18開頭,滿足11位:

 1 public class RegexDemo { 2     public static void main(String[] args) { 3         //鍵盤錄入手機號碼 4         Scanner sc = new Scanner(System.in); 5         System.out.println("請輸入你的手機號碼:"); 6         String phone = sc.nextLine(); 7          8         //定義手機號碼的規則 9         String regex = "1[38]\\d{9}";10         11         //調用功能,判斷即可12         boolean flag = phone.matches(regex);13         14         //輸出結果15         System.out.println("flag:"+flag);16     }17 }

2:驗證郵箱:

 1 /* 2  * 校正郵箱 3  *  4  * 分析: 5  *         A:鍵盤錄入郵箱 6  *         B:定義郵箱的規則 7  *             [email protected] 8  *             [email protected] 9  *             [email protected]10  *             [email protected]11  *             [email protected]12  *         C:調用功能,判斷即可13  *         D:輸出結果14  */15 public class RegexTest {16     public static void main(String[] args) {17         //鍵盤錄入郵箱18         Scanner sc = new Scanner(System.in);19         System.out.println("請輸入郵箱:");20         String email = sc.nextLine();21         22         //定義郵箱的規則23         //String regex = "[a-zA-Z_0-9][email protected][a-zA-Z_0-9]{2,6}(\\.[a-zA-Z_0-9]{2,3})+";24         String regex = "\\[email protected]\\w{2,6}(\\.\\w{2,3})+";25         26         //調用功能,判斷即可27         boolean flag = email.matches(regex);28         29         //輸出結果30         System.out.println("flag:"+flag);31     }32 }

 

java中的Regex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.