Java API —— Pattern類


正則表達式

    寫一個功能實現QQ號碼的校驗。
import java.util.Scanner;

public class RegexDemo01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入您的QQ號碼:");
        String str = sc.nextLine();
        boolean f = queckQQ(str);
        System.out.println("result:"+f);
    }
    public static boolean queckQQ(String qq) {
        boolean flag = true;
        if (qq == null || qq.length() == 0)
            flag = false;
        if (qq.length() >= 5 && qq.length() <= 15){
            if(!qq.startsWith("0")){
                char[] ch = qq.toCharArray();
                for(int i = 0; i < ch.length;i++){
                    char c = ch[i];
                    if (!Character.isDigit(c)){
                        flag = false;
                    }
                }
            }else{
                flag = false;
            }
        }else{
            flag = false;
        }
        return flag;
    }
}
只是一個功能比較簡單的校驗卻需要那么多的代碼,非常的麻煩,下面學習正則表達式。
   
1、正則表達式概述及基本使用
    正則表達式:是指一個用來描述或者匹配一系列符合某個句法規則的字符串的單個字符串。其實就是一種規則。有自己特殊的應用。
import java.util.Scanner;

public class RegexDemo02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入您的QQ號碼:");
        String str = sc.nextLine();
        boolean f = queckQQ(str);
        System.out.println("result:"+f);
    }
    public static boolean queckQQ(String qq) {
        String regex = "[1-9][0-9]{4,14}";
        boolean flag = qq.matches(regex);
        return flag;
       //return qq.matches("[1-9][0-9]{4,14}");
    }
}
 
3、正則表達式的組成規則
        規則字符在java.util.regex Pattern類中    常見組成規則
         ·  字符
            x 表示字符x。舉例:‘a’ 表示字符a
            \\ 表示反斜線字符
            \n 表示新行(換行)符(‘\u000A’)
            \r 表示回車符('\u 000D')               
     · 字符類
            [abc] 表示a 、b、c(簡單類)
            [^abc] 表示任何字符,除了a、b或c(否定)
            [a-zA-Z] 表示a到z 或A到Z,兩頭的字母包括在內(范圍)            
    [0-9] 表示0到9的字符都包括

         ·  預定義字符類
            . 表示任何字符
            \d 表示數字:[0-9]
            \D 表示非數字:[^0-9]
            \w 表示單詞字符:[a-zA-Z_0-9],在正則表達式里面組成單詞的東西必須有這些東西組成
            \W 表示非單詞字符
 
         ·  邊界匹配器
            ^ 表示行的開頭
            $ 表示行的結尾
            \b 表示單詞邊界,就是不是單詞字符的地方。
                舉例:hello world ?haha ;xixi

         ·  數量詞
? X,一次或一次也沒有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超過 m 次
   
 
 
 
 
 
 
 
3、正則表達式的應用
      · 判斷功能  public boolean matches(String regex)       
  · 分割功能  public String[] split(String regex)       
  · 替換功能  public String replaceAll(String regex,String replacement)       
  · 獲取功能  Pattern和Matcher類的使用
 

1)匹配方法  matches

public static boolean matches(String regex, CharSequence input)

編譯給定正則表達式並嘗試將給定輸入與其匹配。

調用此便捷方法的形式

Pattern.matches(regex, input);
與表達式
Pattern.compile(regex).matcher(input).matches() 
的行為完全相同。

如果要多次使用一種模式,編譯一次后重用此模式比每次都調用此方法效率更高。

參數:
regex - 要編譯的表達式
input - 要匹配的字符序列
拋出:
PatternSyntaxException - 如果表達式的語法無效
  舉例1:校驗手機號碼。要求:11位,18或13開頭。
 *                     13436975980
 *  13688886868
 *  13866668888
 *  13456789012
 *  13123456789
 *  18912345678
 *  18886867878
 *  18638833883
import java.util.Scanner;
public class RegexDemo03 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入您的手機號碼:");
        String phone = sc.nextLine();
        boolean f = queckTelPhone(phone);
        System.out.println("result:"+f);
    }
    public static boolean queckTelPhone(String phone) {
        String regex = "1[38]\\d{9}";
        return phone.matches(regex);
    }
}

  舉例2:校驗郵箱。

import java.util.Scanner;
/**
 *          定義郵箱的規則
 *             1517806580@qq.com
 *             liuyi@163.com
 *             linqingxia@126.com
 *             fengqingyang@sina.com.cn
 *             fqy@itcast.cn
 */
public class RegexDemo04 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入您的郵箱:");
        String email = sc.nextLine();
        boolean f = queckEmail(email);
        System.out.println("result:"+f);
    }
    public static boolean queckEmail(String email) {
        String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";
        return email.matches(regex);
    }
}

2)分割功能 split

    public String[] split(CharSequence input, int limit)
圍繞此模式的匹配拆分給定輸入序列。

此方法返回的數組包含輸入序列的子字符串,由匹配此模式的另一子序列或輸入序列的結尾終止。數組中子字符串的順序與其在輸入中出現的順序相同。如果此模式與輸入的任何子序列都不匹配,那么得到的數組僅包含一個元素,即字符串形式的輸入序列。

limit 參數控制應用模式的次數,從而影響結果數組的長度。如果限制 n 大於零,那么模式至多應用 n> - 1 次,數組的長度不大於 n,並且數組的最后條目將包含除最后的匹配定界符之外的所有輸入。如果 n 非正,那么將應用模式的次數不受限制,並且數組可以為任意長度。如果 n 為零,那么應用模式的次數不受限制,數組可以為任意長度,並且將丟棄尾部空字符串。

 
舉例3:            
  百合網,世紀佳緣,珍愛網,QQ
  搜索好友            
  性別:女            
  范圍:"18-24",age>=18 && age<=24
import java.util.Scanner;

public class RegexDemo05 {
    public static void main(String[] args) {
        //定義一個年齡搜索范圍
        String ages = "18-24";
        //定義規則
        String regex = "-";
        //調用方法
        String[] strArray = ages.split(regex);
        //如何得到int類型的呢?
        int startAge = Integer.parseInt(strArray[0]);
        int endAge = Integer.parseInt(strArray[1]);
        //鍵盤錄入年齡
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入你的年齡:");
        int age = sc.nextInt();
        if(age>=startAge && age<=endAge) {
            System.out.println("你就是我想找的");
        }else {
            System.out.println("不符合我的要求,gun");
        }
    }
}

 

  舉例4:直接分割 

public class RegexDemo06 {
    public static void main(String[] args) {
        // 定義一個字符串
        String s1 = "aa,bb,cc";
        // 直接分割
        String[] str1Array = s1.split(",");
        for (int x = 0; x < str1Array.length; x++) {
            System.out.println(str1Array[x]);
        }
        System.out.println("---------------------");
        String s2 = "aa.bb.cc";
        String[] str2Array = s2.split("\\.");
        for (int x = 0; x < str2Array.length; x++) {
            System.out.println(str2Array[x]);
        }
        System.out.println("---------------------");
        String s3 = "aa    bb                cc";
        String[] str3Array = s3.split(" +");
        for (int x = 0; x < str3Array.length; x++) {
            System.out.println(str3Array[x]);
        }
        System.out.println("---------------------");
        //硬盤上的路徑,我們應該用\\替代\
        String s4 = "E:\\JavaSE\\day14\\avi";
        String[] str4Array = s4.split("\\\\");
        for (int x = 0; x < str4Array.length; x++) {
            System.out.println(str4Array[x]);
        }
        System.out.println("---------------------");
    }
}
 
  舉例5:
/*
 * 我有如下一個字符串:"91 27 46 38 50"
 * 請寫代碼實現最終輸出結果是:"27 38 46 50 91"
 * 分析:
 *  A:定義一個字符串
 *  B:把字符串進行分割,得到一個字符串數組
 *  C:把字符串數組變換成int數組
 *  D:對int數組排序
 *  E:把排序后的int數組在組裝成一個字符串
 *  F:輸出字符串
 */
import java.util.Arrays;
public class RegexDemo07 {
    public static void main(String[] args) {
        String s = "91 27 46 38 50";
        String[] strArray = s.split(" ");
        int[] arr = new int[strArray.length];
        for (int x = 0; x < strArray.length; x++){
            arr[x] = Integer.parseInt(strArray[x]);
        }
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        for(int x = 0; x < arr.length; x++){
            sb.append(arr[x]).append(" ");
        }
        String result = sb.toString().trim();
        System.out.println("result:"+result);
    }
}
 
3)替換功能
          String類的public String replaceAll(String regex,String replacement)
    用給定的 replacement 替換此字符串所有匹配給定的正則表達式的子字符串。
public class RegexDemo08 {
    public static void main(String[] args) {
        String s = "helloqq12345worldkh622112345678java";
        String regex = "\\d";
        String ss = "*";
        String result = s.replaceAll(regex,ss);
        System.out.println("result:"+result);
    }
}

 

4)獲取功能
    Pattern和Matcher類的使用
    模式和匹配器的基本使用順序
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo09 {
    public static void main(String[] args) {
        // 模式和匹配器的典型調用順序
        // 把正則表達式編譯成模式對象
        Pattern p = Pattern.compile("a*b");
        // 通過模式對象得到匹配器對象,這個時候需要的是被匹配的字符串
        Matcher m = p.matcher("aaaaab");
        // 調用匹配器對象的功能
        boolean b = m.matches();
        System.out.println(b);
        //以上是判斷功能,太麻煩了,我們直接用字符串的方法做
        String s = "aaaaab";
        String regex = "a*b";
        boolean bb = s.matches(regex);
        System.out.println(bb);
    }
}

 

    舉例:
          獲取下面這個字符串中由三個字符組成的單詞
   da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Created by gao on 15-12-5.
 */
public class RegexDemo10 {
    public static void main(String[] args) {
        // 定義字符串
        String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";
        // 規則 \\b表示單詞邊界,邊界不允許出現單詞字符
        String regex = "\\b\\w{3}\\b";
        // 把規則編譯成模式對象
        Pattern p = Pattern.compile(regex);
        // 通過模式對象得到匹配器對象
        Matcher m = p.matcher(s);
        // 調用匹配器對象的功能
        // 通過find方法就是查找有沒有滿足條件的子串
        // public boolean find()
        while (m.find()) {
            System.out.println(m.group());
        }
        // 注意:一定要先find(),然后才能group()
        // IllegalStateException: No match found
        // String ss = m.group();
        // System.out.println(ss);
    }
}

 


免責聲明!

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



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