常見正則表達式的使用

在寫代碼過程中,常常遇見需要使用正則表達式的情況下,如對爬取的網頁結果進行提取,對字符串進行整理等場景。在實際使用中,經常是用了就查,查完就忘的狀態,所以這裏想對一些常用正則表達式進行一個整理,方便以後使用。
  1. (?=[-+])
/**
exp="3+6-4";
token=["3","+6","-4"];
*/
String[] token=exp.split("(?=[-+])");//exp=3+6-4

2 . 判斷身份證:要麼是15位,要麼是18位,最後一位可以爲字母,並寫程序提出其中的年月日。

/**
*這是一道面試題
*輸出結果:年:1987月:12日:09
*
*/
String id="130681198712092019";

//首先準備判斷是否滿足身份證要求的正則表達式
String regex="(\\d{14})\\w|\\d{17}\\w";
Pattern regular=Pattern.compile(regex);
Matcher matcher=regular.matcher(id);
matcher.matches();//返回boolean類型,判斷是否滿足要求。

//提取年月日
Pattern birthDayRegularPattern=Pattern.compile("(\\d{6})(\\d{8})(.*)");
Matcher matcher1=birthDayRegularPattern.matcher(id);
if(matcher1.matches()){
     Pattern YearMonthDayRegular=Pattern.compile("(\\d{4})(\\d{2})(\\d{2})");
     Matcher matcher2=YearMonthDayRegular.matcher(matcher1.group(2));
    if(matcher2.matches()){
        StringBuilder sb=new StringBuilder();
        sb.append("年:"+matcher2.group(1));
        sb.append("月:"+matcher2.group(2));
        sb.append("日:"+matcher2.group(3));
             }
         }
    }

3 . 只能輸入至少n個數字

/**
*輸出結果:滿足至少7個數字的條件
*
*/
String s="1236789012";
int least=7;
Pattern pattern=Pattern.compile("\\d{"+least+",}");
Matcher matcher=pattern.matcher(s);
if(matcher.matches()){
    System.out.println("滿足至少"+least+"的條件");
}else{
    System.out.println("不滿足至少"+least+"的條件");
        }

4 . 只能輸入n個字符

/**
*注意這裏表達式也可以是"^.{5}$"
*java中\\用於轉移字符,如\\d,\\w(不同語言語法略微不同撒)
*/
Pattern pattern=Pattern.compile(".{5}");
Matcher matcher=pattern.matcher(s);

5 . 只能輸入英文字母

/**
*.表示匹配任意字符
**表示匹配0-n個字符
*+表示匹配1-n個字符
*/
Pattern pattern=Pattern.compile(".[A-Za-z]+");
Matcher matcher=pattern.matcher(s);

6 . 只能輸入英文字符/數字/下劃線

這裏的知識點爲:\\w 

7 . 驗證是否爲漢字

Pattern pattern=Pattern.compile("[\u4e00-\u9fa5]{0,}");
Matcher matcher=pattern.matcher(s);

8 . 驗證手機號(包含159,不包含小靈通)

/**
*這裏主要的知識點爲:{}用來表示前面內容的數量
*
*/
Pattern pattern=Pattern.compile("13[0-9]{1}[0-9]{8}|15[9]{1}[0-9]{8} ");
Matcher matcher=pattern.matcher(s);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章