java 驗證手機號是否合法
一、通用工具類編寫
/** * @project * @Description * @Author songwp * @Date 2022/9/15 17:06 * @Version 1.0.0 **/ public class PhoneUtil { /** * 驗證手機號是否合法 * @return */ public static boolean isMobileNum(String mobile){ if (mobile.length() != 11) { return false; }else{ /** * 移動號段正則表達式 */ String pat1 = "^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$"; /** * 聯(lián)通號段正則表達式 */ String pat2 = "^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$"; /** * 電信號段正則表達式 */ String pat3 = "^((133)|(153)|(177)|(18[0,1,9])|(149))\\d{8}$"; /** * 虛擬運營商正則表達式 */ String pat4 = "^((170))\\d{8}|(1718)|(1719)\\d{7}$"; Pattern pattern1 = Pattern.compile(pat1); Matcher match1 = pattern1.matcher(mobile); boolean isMatch1 = match1.matches(); if(isMatch1){ return true; } Pattern pattern2 = Pattern.compile(pat2); Matcher match2 = pattern2.matcher(mobile); boolean isMatch2 = match2.matches(); if(isMatch2){ return true; } Pattern pattern3 = Pattern.compile(pat3); Matcher match3 = pattern3.matcher(mobile); boolean isMatch3 = match3.matches(); if(isMatch3){ return true; } Pattern pattern4 = Pattern.compile(pat4); Matcher match4 = pattern4.matcher(mobile); boolean isMatch4 = match4.matches(); if(isMatch4){ return true; } return false; } } }
二、方法調(diào)用測試
public static void main(String[] args) { boolean mobileNum = isMobileNum("18740458584"); System.out.println("驗證自己的手機號是否合法:"+mobileNum); boolean mobileNum1 = isMobileNum("1554"); System.out.println("驗證少于11位數(shù)字通過驗證是否合法:"+mobileNum1); boolean mobileNum2 = isMobileNum("1554AAAAAAAAAA"); System.out.println("驗證大于11位數(shù)字且含字母通過驗證是否合法:"+mobileNum2); }
輸出如下:
驗證自己的手機號是否合法:true 驗證少于11位數(shù)字通過驗證是否合法:false 驗證大于11位數(shù)字且含字母通過驗證是否合法:false
古今成大事者,不唯有超世之才,必有堅韌不拔之志!

浙公網(wǎng)安備 33010602011771號