java中的正則操作方法總結(jié)
正則表達(dá)式在處理字符串的效率上是相當(dāng)高的
關(guān)于正則表達(dá)式的使用,更多的是自己的經(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()方法用于按正則表達(dá)式切割,返回一個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)文章
Spring中@Autowired和@Resource注解相同點(diǎn)和不同點(diǎn)
這篇文章主要介紹了Spring中@Autowired和@Resource注解相同點(diǎn)和不同點(diǎn),本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01
淺析Spring IOC bean為什么默認(rèn)是單例
單例的意思就是說在 Spring IoC 容器中只會存在一個 bean 的實例,無論一次調(diào)用還是多次調(diào)用,始終指向的都是同一個 bean 對象,本文小編將和大家一起分析Spring IOC bean為什么默認(rèn)是單例,需要的朋友可以參考下2023-12-12
Spring?AOP?后置通知修改響應(yīng)httpstatus方式
這篇文章主要介紹了Spring?AOP?后置通知修改響應(yīng)httpstatus方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
hibernate 配置數(shù)據(jù)庫方言的實現(xiàn)方法
這篇文章主要介紹了hibernate 配置數(shù)據(jù)庫方言的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
Java實現(xiàn)Jar文件的遍歷復(fù)制與文件追加
這篇文章主要為大家詳細(xì)介紹了如何利用Java實現(xiàn)Jar文件的遍歷復(fù)制與文件追加功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11

