java 检查ssn_Java Regex to Validate SSN (Social Security Numbers)

在此java regex教程中,我们将学习使用正则表达式来测试用户是否在您的应用程序或网站表单中输入了有效的社会安全号码。

Valid SSN Number Format

美国社会安全号码是AAA-GG-SSSS格式的9位数字,具有以下规则。

前三位数字称为区域号。 区域号不能为000、666或900到999之间。

数字4和5称为组号,范围从01到99。

后四位数字是从0001到9999的序列号。

为了验证以上3条规则,我们的正则表达式为:Regex : ^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$

Explanation of Regex of Validate SSN^ # Assert position at the beginning of the string.

(?!000|666) # Assert that neither "000" nor "666" can be matched here.

[0-8] # Match a digit between 0 and 8.

[0-9]{2} # Match a digit, exactly two times.

- # Match a literal "-".

(?!00) # Assert that "00" cannot be matched here.

[0-9]{2} # Match a digit, exactly two times.

- # Match a literal "-".

(?!0000) # Assert that "0000" cannot be matched here.

[0-9]{4} # Match a digit, exactly four times.

$ # Assert position at the end of the string.

现在,让我们使用一些演示SSN编号测试我们的SSN验证正则表达式。List ssns = new ArrayList();

//Valid SSNs

ssns.add("123-45-6789");

ssns.add("856-45-6789");

//Invalid SSNs

ssns.add("000-45-6789");

ssns.add("666-45-6789");

ssns.add("901-45-6789");

ssns.add("85-345-6789");

ssns.add("856-453-6789");

ssns.add("856-45-67891");

ssns.add("856-456789");

String regex = "^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$";

Pattern pattern = Pattern.compile(regex);

for (String number : ssns)

{

Matcher matcher = pattern.matcher(number);

System.out.println(matcher.matches());

}

Output:

true

true

false

false

false

false

false

false

false

我建议您使用上述简单的正则表达式尝试更多的变化。

Happy Learning !!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值