Java學習筆記21(String類補充:Regex),學習筆記string
正如python的re模組,不過Java和Python的Regex有一些區別,這裡做簡單介紹,具體的細節可以參考網上其他的文章:
功能:可以用於檢驗一個字串,比如驗證使用者名稱,驗證密碼格式,驗證是否是郵箱,等等
樣本:
"[0-9]{6,12}"匹配規則:6到12位的數字,比如123456789就是true,12345就是false
"1[3578][0-9]{9}"匹配規則:1開頭,第二位是3578中的一個,後面九個任一數字,比如13345678912就是true
"a*b"匹配規則:在多個a或者0個a之後有一個b,b必須是最後一個字元,比如aaaaab就是true,abc就是false
String類中還有幾個方法上篇沒有提到,這裡會用到
基礎知識不再介紹,樣本:
matches方法:
package demo;public class RegexDemo { public static void main(String[] args) { //檢查QQ號碼,不能0開頭,全數字,5位到10位 checkQQ(); //檢查手機號,1開頭,第二位是34578,共11位 checkTel(); } public static void checkQQ(){ String QQ = "123456"; boolean b = QQ.matches("[1-9][\\d]{4,9}"); System.out.println(b);//true } public static void checkTel(){ String telNumber = "13312345678"; boolean b = telNumber.matches("1[34578][\\d]{9}"); System.out.println(b);//true }}
split方法:
package demo;public class RedexDemo { public static void main(String[] args) { split_1(); split_2(); split_3(); } public static void split_1(){ String str = "I love java"; String[] strArr = str.split(" +"); for (int i = 0; i < strArr.length; i++) { System.out.println(strArr[i]); } //列印出:I love java } public static void split_2(){ String str = "10-12-45-78-62"; String[] strArr = str.split("-"); for (int i = 0; i < strArr.length; i++) { System.out.println(strArr[i]); } //列印出:10 12 45 78 62 } public static void split_3(){ String str = "192.168.160.1"; String[] strArr = str.split("\\."); for (int i = 0; i < strArr.length; i++) { System.out.println(strArr[i]); } //列印出:192 168 160 1 }}
replaceAll方法:
package demo;public class RedexDemo { public static void main(String[] args) { replaceAll_1(); } public static void replaceAll_1(){ String str = "Hello666123Ilove789java"; String str1 = str.replaceAll("[\\d+]","#"); System.out.println(str1); //輸出:Hello######Ilove###java String str2 = str.replaceAll("[\\d]+", "#"); System.out.println(str2); //輸出:Hello#Ilove#java }}
Regex練習:
package demo;public class RedexDemo { public static void main(String[] args) { //檢查郵箱地址 checkMail(); } public static void checkMail(){ String email = "abc123@sina.com.cn"; boolean b = email.matches("[a-zA-Z0-9_]+@[0-9a-z]+(\\.[a-z]+)+"); System.out.println(b);//true }}