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