原文: 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 正则表达式的说明

  1. ^ # Assert position at the beginning of the string.
  2. (?!000|666) # Assert that neither "000" nor "666" can be matched here.
  3. [0-8] # Match a digit between 0 and 8.
  4. [0-9]{2} # Match a digit, exactly two times.
  5. - # Match a literal "-".
  6. (?!00) # Assert that "00" cannot be matched here.
  7. [0-9]{2} # Match a digit, exactly two times.
  8. - # Match a literal "-".
  9. (?!0000) # Assert that "0000" cannot be matched here.
  10. [0-9]{4} # Match a digit, exactly four times.
  11. $ # Assert position at the end of the string.

现在,我们使用一些演示 SSN 编号测试我们的 SSN 验证正则表达式。

  1. List<String> ssns = new ArrayList<String>();
  2. //Valid SSNs
  3. ssns.add("123-45-6789");
  4. ssns.add("856-45-6789");
  5. //Invalid SSNs
  6. ssns.add("000-45-6789");
  7. ssns.add("666-45-6789");
  8. ssns.add("901-45-6789");
  9. ssns.add("85-345-6789");
  10. ssns.add("856-453-6789");
  11. ssns.add("856-45-67891");
  12. ssns.add("856-456789");
  13. String regex = "^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$";
  14. Pattern pattern = Pattern.compile(regex);
  15. for (String number : ssns)
  16. {
  17. Matcher matcher = pattern.matcher(number);
  18. System.out.println(matcher.matches());
  19. }
  20. Output:
  21. true
  22. true
  23. false
  24. false
  25. false
  26. false
  27. false
  28. false
  29. false

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

学习愉快!