大家都知道,正則表達式是一種可以用于模式匹配和替換的規范,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作為一個模板,將某個字符模式與所搜索的字符串進行匹配。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/** * 手機號:目前全國有27種手機號段。 * 移動有16個號段:134、135、136、137、138、139、147、150、151、152、157、158、159、182、187、188。其中147、157、188是3G號段,其他都是2G號段。 * 聯通有7種號段:130、131、132、155、156、185、186。其中186是3G(WCDMA)號段,其余為2G號段。 * 電信有4個號段:133、153、180、189。其中189是3G號段(CDMA2000),133號段主要用作無線網卡號。 * 150、151、152、153、155、156、157、158、159 九個; * 130、131、132、133、134、135、136、137、138、139 十個; * 180、182、185、186、187、188、189 七個; * 13、15、18三個號段共30個號段,154、181、183、184暫時沒有,加上147共27個。 */ private boolean telCheck(String tel){ Pattern p = Pattern.compile( "^((13\\d{9}$)|(15[0,1,2,3,5,6,7,8,9]\\d{8}$)|(18[0,2,5,6,7,8,9]\\d{8}$)|(147\\d{8})$)" ); Matcher m = p.matcher(tel); return m.matches(); } |
Java正則表達式驗證格式(郵箱、電話號碼)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package com.firewolf.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 使用正則表達式驗證輸入格式 * @author liuxing * */ public class RegexValidateUtil { public static void main(String[] args) { System.out.println(checkEmail( "14_8@qw.df" )); System.out.println(checkMobileNumber( "071-3534452" )); } /** * 驗證郵箱 * @param email * @return */ public static boolean checkEmail(String email){ boolean flag = false ; try { String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$" ; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(email); flag = matcher.matches(); } catch (Exception e){ flag = false ; } return flag; } /** * 驗證手機號碼 * @param mobiles * @return */ public static boolean checkMobileNumber(String mobileNumber){ boolean flag = false ; try { Pattern regex = Pattern.compile( "^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$" ); Matcher matcher = regex.matcher(mobileNumber); flag = matcher.matches(); } catch (Exception e){ flag = false ; } return flag; } } |