基于java中正則操作的方法總結(jié)
正則表達式在處理字符串的效率上是相當(dāng)高的
關(guān)于正則表達式的使用,更多的是自己的經(jīng)驗,有興趣可以參閱相關(guān)書籍
這里主要寫一下java中的正則操作方法
實例1:匹配import java.util.Scanner;
class Demo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //獲取輸入
        System.out.print("Please Enter:");
        String str = sc.nextLine();
        check(str);
    }
    private static void check(String str) {
        //匹配第一位是1-9,第二位及以后0-9(個數(shù)在4-10之間)
        String regex = "[1-9][0-9]{4,10}";
        /*
        //匹配單個字符是大小寫的a-z
        String regex = "[a-zA-Z]";
        //匹配數(shù)字,注意轉(zhuǎn)義字符
        String regex = "\\d";
        //匹配非數(shù)字
        String regex = "\\D";
        */
        if(str.matches(regex)) {
            System.out.println("匹配成功");
        } else {
            System.out.println("匹配失敗");
        }
    }
}
此處String類中的matches()方法用于匹配

實例2:切割
import java.util.Scanner;
class Demo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Please Enter:");
        String str = sc.nextLine();
        split(str);
    }
    private static void split(String str) {
        //匹配一個或多個空格
        String regex = " +";
        String[] arr = str.split(regex);
        for (String s : arr) {
            System.out.println(s);
        }
    }
}
此處String類中的split()方法用于按正則表達式切割,返回一個String數(shù)組

實例3:替換
import java.util.Scanner;
class Demo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Please Enter:");
        String str = sc.nextLine();
        replace(str);
    }
    private static void replace(String str) {
        //匹配疊詞
        String regex = "(.)\\1+";
        String s = str.replaceAll(regex, "*");
        System.out.println(s);
    }
}
注意replaceAll有兩個參數(shù),一個是正則,一個是替換的字符

相關(guān)文章
 IntelliJ IDEA的build path設(shè)置方法
這篇文章主要介紹了IntelliJ IDEA的build path設(shè)置方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
 springboot集成shiro遭遇自定義filter異常的解決
這篇文章主要介紹了springboot集成shiro遭遇自定義filter異常的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
 Java多線程循環(huán)柵欄CyclicBarrier正確使用方法
這篇文章主要介紹了Java多線程循環(huán)柵欄CyclicBarrier正確使用方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
 MyBatis中批量插入和批量更新的實現(xiàn)方法詳解
這篇文章主要介紹了MyBatis中批量插入和批量更新的實現(xiàn)方法,在日常開發(fā)中有時候需要從A數(shù)據(jù)庫提取大量數(shù)據(jù)同步到B系統(tǒng),這種情況自然是需要批量操作才行,感興趣想要詳細了解可以參考下文2023-05-05
 Spring Security實現(xiàn)微信公眾號網(wǎng)頁授權(quán)功能
這篇文章主要介紹了Spring Security中實現(xiàn)微信網(wǎng)頁授權(quán),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08

