1. 程式人生 > >正則表示式基礎2

正則表示式基礎2

註釋:正則表示式的學習記錄2

常見表示式

​ boolean: matches(String regex),稱為匹配字串,其中regex是正則的規則,表示式返回boolean型別值告知此字串是否匹配給定的正則表示式。用法例如,"abc".matches("[a]") 匹配成功返回true

​ String[]: split(String regex),稱為切割字串,其中regex是正則的規則,根據給定正則表示式的匹配拆分此字串。

​ String: replaceALL(String regex,String replacement),稱為替換字串,其中regex是正則的規則,使用給定的replacement替換此字串所有匹配給定的正則表示式的子字串。

幾個例子

例1.校驗手機號碼,要求:

1、要求為11位數字
2、要求第一位為1,第二位為3、4、5、7、8中的一個,後面9位為0到9之間的任意數字。
程式碼演示
public static void main(String[] args) {
    checkphone();
}
/*
 * 本函式用於檢查手機號碼是否合法,具體實現:
 * 1.11位數字;2.要求第一位為1,第二位為3、4、5、7、8中的一個,後面9位為0到9之間的任意數字。
 */
 public static void checkphone(){
     Scanner input = new Scanner
(System.in);
System.out.println("請輸入手機號:"); String phone = input.next(); String regex = "1[34578][0-9]{9}"; //檢查手機號碼和規則是否匹配,String類的方法matches boolean b = phone.matches(regex); //當輸出的布林型為true時,表示所輸入的手機號正確,反之輸入錯誤 System.out.println(b); if(b==true){ System.out
.print("手機號碼輸入正確!");
}else{ System.out.print("手機號碼輸入錯誤!"); } } }
輸出結果

結果1請輸入手機號:12345678false手機號碼輸入錯誤! 結果2請輸入手機號:18677456879true手機號碼輸入正確!

例2.分割出字串中的數字,從字串"18-46-21-73"中提取出數字

程式碼演示
import java.util.Arrays;
//通過正則拆分函式從字串中拆分出數字
public class RegexDemo2 {
   public static void main(String[] args) {
       String sc = "18-46-21-73";   //給定原字串
       String regex = "-";   //拆分正則規則
       String[] fc = sc.split(regex);   //拆分結果
       System.out.print(Arrays.toString(fc));   //列印輸出結果
   }
}
輸出結果

[18, 46, 21, 73]

例3.把文字中的數字替換成%,將所給的字串"Welcome743 42the4 World887!"中的數字替換成%

程式碼演示
//將所給的字串中的數字替換成%
public class RegexDemo3 {
   public static void main(String[] args) {
       String sc ="Welcome743 42the4 World887!";   //給定原字串
       String regex = "[0-9]";   //替換規則
       String result = sc.replaceAll(regex, "%");    //替換
       System.out.print(result);    //列印輸出結果
   }
}
輸出結果

Welcome%%% %%the% World%%%!

例4.匹配正確的數字

匹配規則:(不考慮0)
匹配正整數:”\\d+
匹配正小數:”\\d+\\.\\d+  
匹配負整數:”-\\d+
匹配負小數:”-\\d+\\.\\d+
匹配保留兩位小數的正數:”\\d+\\.\\d{2}
匹配保留1-3位小數的正數:”\\d+\\.\\d{1,3}
程式例項
import java.util.Scanner;
public class RegexDemo4 {
    /**
     根據要求匹配數字
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("請輸入一個正整數:");
        String number1 = input.next();   //輸入一個數字
        String regex = "\\d+";   //匹配正則規則
        boolean b = number1.matches(regex);  //匹配數字
        System.out.println(b);    //列印結果,true則符合要求
    }
}
輸出結果

請輸入一個正整數:39true

例5.獲取IP地址:匹配規則 ”\.”

程式例項
import java.util.Arrays;
public class RegexDemo5 {
    /**
     *獲取IP地址(192.168.1.100)中的每段數字
     */
    public static void main(String[] args) {
        String sc = "192.168.1.100";   //給定原字串
        String regex = "\\.";   //拆分正則規則
        String[] fc = sc.split(regex);   //拆分結果
        System.out.print(Arrays.toString(fc));   //列印輸出結果
    }
}
輸出結果

[192, 168, 1, 100]