關於Java中的正則表達式匹配


正則簡單示例:

在線正則表達式網址:https://any86.github.io/any-rule/

java.util.regex是一個用正則表達式所訂制的模式來對字符串進行匹配工作的類庫包。它包括兩個類:

    Pattern:Pattern是一個正則表達式經編譯后的表現模式

    Matcher:Matcher對象是一個狀態機器,它依據Pattern對象做為匹配模式對字符串展開匹配檢查

public static void main(String[] args) {
    /*定義要進行驗證的手機號碼*/
    String cellPhoneNumber = "15817784252";
    /*定義手機號碼正則*/
    String phoneRegex = "^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[189]))\\d{8}$";
    /*
      第一種:使用String類
      說明此字符串是否與給定的正則表達式匹配。
      參數: regex–此字符串要與之匹配的正則表達式
      返回值: 當且僅當此字符串與給定正則表達式匹配時為true
     */
    boolean stringMatches = cellPhoneNumber.matches(phoneRegex);
    System.out.println("使用String類進行比較結果:" + stringMatches);

    /*第二種:使用Pattern
     * 將給定的正則表達式編譯為模式。
     * 參數: regex–要編譯的表達式
     * 返回值: 已編譯為模式的給定正則表達式
     * */
    Pattern pattern = Pattern.compile(phoneRegex);
    /*創建一個匹配器,該匹配器將根據此模式匹配給定的輸入。 參數: 輸入–要匹配的字符序列*/
    Matcher matcher = pattern.matcher(cellPhoneNumber);
    /*字符串是否與正則表達式相匹配*/
    boolean patternMatches = matcher.matches();
    System.out.println("使用Pattern類的matcher進行比較結果:" + patternMatches);

    /*第三種:使用Pattern的兩個參數構造器
    * 參數1: 正則表達式
    * 參數2: 要匹配的字符序列
    * 返回值: 正則表達式是否與輸入匹
    * */
    boolean constructorMatches = Pattern.matches(phoneRegex, cellPhoneNumber);
    System.out.println("使用Pattern類的matcher重載進行比較結果" + constructorMatches);
}

判斷字符串中是否包含數字

// 判斷字符串包含數字 方法一
    public static boolean testIsNumMethodOne(String str) {
        boolean flag = false;
        String numStr = "0123456789";
        for (int i = 0; i < str.length(); i++) {
            String subStr = str.substring(i, i+1);
            if (numStr.contains(subStr)) {
                flag = true;
            }
        }
        return flag;
    }
    
    // 判斷字符串包含數字 方法二
    public static boolean testIsNumMethodTwo(String str) {
        boolean flag = false;
        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            flag = true;
        }
        return flag;
    }
    
    // 判斷字符串包含數字 方法三
    public static boolean testIsNumMethodThree(String str) {
        boolean flag = false;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c > 48 && c < 57) {
                flag = true;
            }
        }
        return flag;
    }
    
    // 判斷字符串包含數字 方法四
    public static boolean testIsNumMethodFour(String str) {
        boolean flag = false;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isDigit(c)) {
                flag = true;
            }
        }
        return flag;
    }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM