您的位置:首页 > 编程语言 > Java开发

java中使用正则对格式的验证

2014-12-31 23:52 148 查看
import java.util.regex.*;

public final class RegExpValidator {

public static boolean isEmail(String str) {

String regex = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

return match(regex, str);

}

public static boolean isIP(String str) {

String regex = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";

return match(regex, str);

}

@Deprecated

public static boolean IsUrl(String str) {

str = str.toLowerCase();

//String regex = "^(http|www|ftp|https|)?(://)?(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*((:\\d+)?)(/(\\w+(-\\w+)*))*(\\.?(\\w)*)(\\?)?(((\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*(\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*)*(\\w*)*)$";

String regex = "^http://[\\w-\\.]+(?:/|(?:/[\\w\\.\\-]+)*(?:/[\\w\\.\\-]+\\.*))?$";

return match(regex, str);

}

public static boolean isTelephone(String str) {

String regex = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";

return match(regex, str);

}

public static boolean isPostalcode(String str) {

String regex = "[1-9]\\d{5}(?!\\d)";

return match(regex, str);

}

public static boolean isIDcard(String str) {

String regex = "(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])";

return match(regex, str);

}

public static boolean isDate(String str) {

String regex = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";

return match(regex, str);

}

private static boolean match(String regex, String str) {

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(str);

return matcher.matches();

}

public static void main(String[] args) {

System.out.println(RegExpValidator.isEmail("448117419@qq.com"));

System.out.println(RegExpValidator.isIP("192.168.1.123"));

System.out.println(RegExpValidator.isDate("2012-10-10"));

System.out.println(RegExpValidator

.IsUrl("HTTP://www.baidu.nn/hello.do"));

System.out.println(RegExpValidator.isTelephone("13522349251"));

System.out.println(RegExpValidator.isPostalcode("417000"));

System.out.println(RegExpValidator.isIDcard("431221199110020817"));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: