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

本文介绍了一组使用正则表达式进行验证的常见数据类型,包括邮箱、IP地址、URL、电话号码、邮编、身份证号和日期格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
 }
 @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);
 }
 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"));
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值