java中的正則操作方法總結(jié)
正則表達(dá)式在處理字符串的效率上是相當(dāng)高的
關(guān)于正則表達(dá)式的使用,更多的是自己的經(jīng)驗(yàn),有興趣可以參閱相關(guān)書籍
這里主要寫一下java中的正則操作方法
實(shí)例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(個(gè)數(shù)在4-10之間)
String regex = "[1-9][0-9]{4,10}";
/*
//匹配單個(gè)字符是大小寫的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()方法用于匹配
實(shí)例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) {
//匹配一個(gè)或多個(gè)空格
String regex = " +";
String[] arr = str.split(regex);
for (String s : arr) {
System.out.println(s);
}
}
}
此處String類中的split()方法用于按正則表達(dá)式切割,返回一個(gè)String數(shù)組
實(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有兩個(gè)參數(shù),一個(gè)是正則,一個(gè)是替換的字符
相關(guān)文章
JAVA CountDownLatch與thread-join()的區(qū)別解析
這篇文章主要介紹了JAVA CountDownLatch與thread-join()的區(qū)別解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08Spring?Boot?RestController接口輸出到終端的操作代碼
這篇文章主要介紹了Spring?Boot?RestController接口如何輸出到終端,使用?HttpServletResponse?類,可以在使用curl執(zhí)行?Spring?Boot?REST接口的同時(shí),在控制臺輸出一些信息,給運(yùn)維人員知道當(dāng)前命令執(zhí)行的狀態(tài),感興趣的朋友跟隨小編一起看看吧2023-09-09教您如何3分鐘快速搞定EasyExcel導(dǎo)入與導(dǎo)出功能
對于EasyExcel庫,我們可以使用它來實(shí)現(xiàn)數(shù)據(jù)的導(dǎo)入和導(dǎo)出,下面這篇文章主要給大家介紹了關(guān)于如何3分鐘快速搞定EasyExcel導(dǎo)入與導(dǎo)出功能的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01Java+Ajax實(shí)現(xiàn)的用戶名重復(fù)檢驗(yàn)功能實(shí)例詳解
這篇文章主要介紹了Java+Ajax實(shí)現(xiàn)的用戶名重復(fù)檢驗(yàn)功能,結(jié)合實(shí)例形式詳細(xì)分析了java針對用戶名提交的ajax數(shù)據(jù)庫查詢與重復(fù)檢查功能相關(guān)實(shí)現(xiàn)技巧與操作注意事項(xiàng),需要的朋友可以參考下2018-12-12