一、什麼是正則表達式
正則表達式是指一個規則表達式,用於描述符合某些特定規則的字符串。通過正則表達式可以方便地進行字符串匹配和替換操作。
在Java中,可以使用Java.util.regex包下的類實現正則表達式的使用。
二、正則表達式的基本語法
在Java中,通過Pattern和Matcher兩個類來組合使用正則表達式。
// 創建Pattern對象
Pattern pattern = Pattern.compile("正則表達式規則");
// 創建Matcher對象
Matcher matcher = pattern.matcher("需要匹配的字符串");
正則表達式規則由普通字符和轉義字符兩種組合而成,其中常用的轉義字符如下:
- \\d:匹配任意數字
- \\w:匹配任意字母、數字、下劃線
- \\s:匹配任意空白字符,包括空格、製表符等
- \\D:匹配除數字以外的任意字符
- \\W:匹配除字母、數字、下劃線以外的任意字符
- \\S:匹配除空白字符以外的任意字符
特殊字符可以放在方括號內表示範圍,如[1-9]表示匹配1~9之間的任意一個數字。
三、常見的正則表達式校驗
1、校驗郵箱地址
校驗郵箱地址是否合法,可以使用如下正則表達式:
String email = "example@example.com";
Pattern pattern = Pattern.compile("^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$");
Matcher matcher = pattern.matcher(email);
if(matcher.matches()){
System.out.println("郵箱地址合法");
}else{
System.out.println("郵箱地址不合法");
}
2、校驗手機號碼
校驗手機號碼是否合法,可以使用如下正則表達式:
String phoneNumber = "13812345678";
Pattern pattern = Pattern.compile("^1[3-9]\\d{9}$");
Matcher matcher = pattern.matcher(phoneNumber);
if(matcher.matches()){
System.out.println("手機號碼合法");
}else{
System.out.println("手機號碼不合法");
}
3、校驗身份證號碼
校驗身份證號碼是否合法,可以使用如下正則表達式:
String idCard = "330301199001011234";
Pattern pattern = Pattern.compile("^\\d{17}[\\dxX]$");
Matcher matcher = pattern.matcher(idCard);
if(matcher.matches()){
System.out.println("身份證號碼合法");
}else{
System.out.println("身份證號碼不合法");
}
4、校驗密碼強度
校驗密碼強度是否符合要求,可以使用如下正則表達式:
String password = "1qaz@WSX";
int strong = 0;
Pattern pattern = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$");
Matcher matcher = pattern.matcher(password);
if(matcher.matches()){
if(Pattern.compile("\\d").matcher(password).find()){
strong ++;
}
if(Pattern.compile("[a-z]").matcher(password).find()){
strong ++;
}
if(Pattern.compile("[A-Z]").matcher(password).find()){
strong ++;
}
if(strong < 2){
System.out.println("密碼強度較弱");
}else if(strong == 2){
System.out.println("密碼強度一般");
}else{
System.out.println("密碼強度較強");
}
}else{
System.out.println("密碼格式不正確");
}
四、總結
本文介紹了正則表達式在Java中的基本語法和常見的使用場景,包括郵箱地址、手機號碼、身份證號碼和密碼強度等校驗。通過正則表達式的強大功能,可以方便地進行字符串匹配和替換操作,提高代碼的效率。
原創文章,作者:REWX,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/141000.html
微信掃一掃
支付寶掃一掃