基于java中正則操作的方法總結(jié)
正則表達(dá)式在處理字符串的效率上是相當(dāng)高的
關(guān)于正則表達(dá)式的使用,更多的是自己的經(jīng)驗,有興趣可以參閱相關(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(個數(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()方法用于匹配

實(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) {
//匹配一個或多個空格
String regex = " +";
String[] arr = str.split(regex);
for (String s : arr) {
System.out.println(s);
}
}
}
此處String類中的split()方法用于按正則表達(dá)式切割,返回一個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有兩個參數(shù),一個是正則,一個是替換的字符

相關(guān)文章
java實(shí)現(xiàn)文件分片上傳并且斷點(diǎn)續(xù)傳的示例代碼
本文主要介紹了java實(shí)現(xiàn)文件分片上傳并且斷點(diǎn)續(xù)傳的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
JAVA Frame 窗體背景圖片,首位相接滾動代碼實(shí)例
這篇文章主要介紹了JAVA Frame 窗體背景圖片,首位相接滾動代碼示例,需要的朋友可以參考下復(fù)制代碼2017-04-04
Spring Boot + Mybatis-Plus實(shí)現(xiàn)多數(shù)據(jù)源的方法
這篇文章主要介紹了Spring Boot + Mybatis-Plus實(shí)現(xiàn)多數(shù)據(jù)源的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
Java鏈表中元素刪除的實(shí)現(xiàn)方法詳解【只刪除一個元素情況】
這篇文章主要介紹了Java鏈表中元素刪除的實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了java只刪除鏈表中一個元素的相關(guān)操作原理、實(shí)現(xiàn)方法與注意事項,需要的朋友可以參考下2020-03-03

