下面給大家介紹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
|
/** * 驗證固定電話號碼的合法性 * @author jy */ package phone; import java.util.regex.matcher; import java.util.regex.pattern; public class phonetest { public static boolean isphone(string str) { pattern p1 = null , p2 = null ; matcher m = null ; boolean isphone = false ; p1 = pattern.compile( "^[0][1-9]{2,3}-[0-9]{5,10}$" ); // 驗證帶區號的 p2 = pattern.compile( "^[1-9]{1}[0-9]{5,8}$" ); // 驗證沒有區號的 if (str.length() > 9 ) { m = p1.matcher(str); isphone = m.matches(); } else { m = p2.matcher(str); isphone = m.matches(); } return isphone; } public static void main(string[] args) { string phone = "0770-88889999" ; if (isphone(phone)){ system.out.println(phone+ "是符合的電話號碼" ); } else { system.out.println(phone+ "不符合" ); } } } |
下面看下用正則表達式判斷一個字符串是否全是數字
用正則表達式首先要import java.util.regex.pattern 和 java.util.regex.matcher
1
2
3
4
5
6
7
8
|
public boolean isnumeric(string str){ pattern pattern = pattern.compile( "[0-9]*" ); matcher isnum = pattern.matcher(str); if ( !isnum.matches() ){ return false ; } return true ; } |
PS:推薦2款在線正則表達式工具,有需要的朋友可以看看
正則表達式在線測試工具 https://tool.zzvips.com/t/regex/
正則表達式生成器 https://tool.zzvips.com/t/regcode/
總結
以上所述是小編給大家介紹的java正則表達式驗證固定電話號碼符合性,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/weixin_41888813/article/details/82492220