验证 SSN(社会安全号码)的 Java 正则表达式

验证 SSN(社会安全号码)的 Java 正则表达式

原文: https://howtodoinjava.com/regex/java-regex-validate-social-security-numbers-ssn/

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

有效的 SSN 编号格式

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

  • 前三位数字称为区域号。 区域号不能为 000、666 或 900 到 999 之间。
  • 数字 4 和 5 称为组号,范围从 01 到 99。
  • 后四位数字是从 0001 到 9999 的序列号。

为了验证以上 3 条规则,我们的正则表达式为:

正则表达式:^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$

验证 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<String> ssns = new ArrayList<String>();

//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

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

学习愉快!