在此 java 正则表达式教程中,我们将学习使用正则表达式来测试用户是否在您的应用程序或网站表单中输入了有效的社会安全号码,接下来我们就来聊聊关于如何用正则表达式产生四位验证码?以下内容大家不妨参考一二希望能帮到您!

如何用正则表达式产生四位验证码(验证SSN社会安全号码)

如何用正则表达式产生四位验证码

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

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

有效的 SSN 编号格式

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

为了验证以上 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

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

Q.E.D.

,