一个通用且常用的Java正则匹配工具,用以检查邮箱名、电话号码、用户密>码、邮政编码等合法性。
*(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小)
验证Email
public static boolean checkEmail(String email) {
String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";
return Pattern.matches(regex, email);
}
验证身份证号码
public static boolean checkIdCard(String idCard)
{
String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}";
return Pattern.matches(regex,idCard);
}
*验证手机号码
public static boolean checkMobile(String mobile) {
String regex = "(\\+\\d+)?1[3458]\\d{9}$";
return Pattern.matches(regex,mobile);
}
*验证固定电话号码
public static boolean checkPhone(String phone) {
String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$";
return Pattern.matches(regex, phone);
}
*验证整数(正整数和负整数)
public static boolean checkDigit(String digit) {
String regex = "\\-?[1-9]\\d+";
return Pattern.matches(regex,digit);
}
*验证整数和浮点数(正负整数和正负浮点数)
public static boolean checkDecimals(String decimals) {
String regex = "\\-?[1-9]\\d+(\\.\\d+)?";
return Pattern.matches(regex,decimals);
}
*验证空白字符
public static boolean checkBlankSpace(String blankSpace) {
String regex = "\\s+";
return Pattern.matches(regex,blankSpace);
}
*验证中文
public static boolean checkChinese(String chinese) {
String regex = "^[\u4E00-\u9FA5]+$";
return Pattern.matches(regex,chinese);
}
*验证日期(年月日)
public static boolean checkBirthday(String birthday) {
String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}";
return Pattern.matches(regex,birthday);
}
*验证URL地址
public static boolean checkURL(String url) {
String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?";
return Pattern.matches(regex, url);
}
*获取网址 URL 的一级域名
public static String getDomain(String url) {
Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);
// 获取完整的域名
// Pattern p=Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(url);
matcher.find();
return matcher.group();
}
*匹配中国邮政编码
public static boolean checkPostcode(String postcode) {
String regex = "[1-9]\\d{5}";
return Pattern.matches(regex, postcode);
}
*匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小)
public static boolean checkIpAddress(String ipAddress) {
String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))";
return Pattern.matches(regex, ipAddress);
}
*是否包含 . 号
public static boolean checkContainsDot(String username) {
return username.contains(".");
}
*是否包含连词符
public static boolean checkContainsHyphen(String username) {
return username.contains("-");
}
*密码长度 6-20
public static boolean checkUserPasswordLength(String pwd) {
return pwd.length() > 5 && pwd.length() <21;
}
*匹配用户名
public static boolean isValidUserName(String un)
{
String regex = "([A-Z0-9a-z-]|[\\u4e00-\\u9fa5])+";
return Pattern.matches(regex, un);
}
}