使用正则表达式进行特定字符串验证

时间:2017-05-09 20:06:43

标签: java regex validation constraints

我被告知要使用正则表达式而不是isUpperCase()isLowerCase()等...但我不知道如何使用正则表达式。

这是我需要检查的:

length min = 8 characters
length max = 20 characters
must contain at least one lower case character (a-z)
must contain at least one upper case character (A-Z)
must contain at least one number (0-9)
must contain at least one special character

感谢。

3 个答案:

答案 0 :(得分:1)

如果你想学习,如何使用正则表达式,我推荐以下

  • 阅读您的讲义
  • 阅读一本Java书(特别是关于“模式”和“正则表达式”的章节)
  • 阅读Java文档,例如关于Pattern

答案 1 :(得分:0)

大写的正则表达式为[A-Z],小写的正则表达式为[a-z] 两个测试至少发生给定char组的一次。

答案 2 :(得分:0)

注意:我没有在Java中对此进行测试,但这适用于pcre引擎。

^(?=.{8,20}$)(?=[^A-Z]*?[A-Z])(?=[^a-z]*?[a-z])(?=[^0-9]*?[0-9])(?=[^!@#$%^&*]*?[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]+$

细分:

    ^(?=.{8,20}$)               //this matches 8 to 20 characters, inclusive (positive lookahead)
    (?=[^A-Z]*?[A-Z])           //this matches if one uppercase letter is present (positive lookahead)
    (?=[^a-z]*?[a-z])           //this matches if one lowercase letter is present (positive lookahead)
    (?=[^0-9]*?[0-9])           //this matches if one digit is present (positive lookahead)
    (?=[^!@#$%^&*]*?[!@#$%^&*]) //this matches if one special character is present (positive lookahead)
    [a-zA-Z0-9!@#$%^&*]+$       //this matches if the enclosed characters are present

对于你想要的东西,这可能有点过头,但我在这里测试了它: https://regex101.com/r/P0J4X8/1

此外,在前瞻

中可能不需要延迟评估者