java中的正則操作方法總結
正則表達式在處理字符串的效率上是相當高的
關于正則表達式的使用,更多的是自己的經(jīng)驗,有興趣可以參閱相關書籍
這里主要寫一下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ù)字,注意轉義字符
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ù),一個是正則,一個是替換的字符
相關文章
JAVA CountDownLatch與thread-join()的區(qū)別解析
這篇文章主要介紹了JAVA CountDownLatch與thread-join()的區(qū)別解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-08-08Spring?Boot?RestController接口輸出到終端的操作代碼
這篇文章主要介紹了Spring?Boot?RestController接口如何輸出到終端,使用?HttpServletResponse?類,可以在使用curl執(zhí)行?Spring?Boot?REST接口的同時,在控制臺輸出一些信息,給運維人員知道當前命令執(zhí)行的狀態(tài),感興趣的朋友跟隨小編一起看看吧2023-09-09Java+Ajax實現(xiàn)的用戶名重復檢驗功能實例詳解
這篇文章主要介紹了Java+Ajax實現(xiàn)的用戶名重復檢驗功能,結合實例形式詳細分析了java針對用戶名提交的ajax數(shù)據(jù)庫查詢與重復檢查功能相關實現(xiàn)技巧與操作注意事項,需要的朋友可以參考下2018-12-12