下面给大家介绍Java正则表达式验证固定电话号码符合性,具体代码如下所示:
/**
* 验证固定电话号码的合法性
* @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 = pile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
p2 = pile("^[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
public boolean isNumeric(String str){
Pattern pattern = pile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() ){
return false;
}
return true;
}
总结
以上所述是小编给大家介绍的Java正则表达式验证固定电话号码符合性,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!