代码之家  ›  专栏  ›  技术社区  ›  Amarghosh

regex确保字符串至少包含一个小写字符、大写字符、数字和符号

  •  125
  • Amarghosh  · 技术社区  · 15 年前

    什么是regex,以确保给定的字符串至少包含以下每个类别中的一个字符。

    • 小写字符
    • 大写字符
    • 数字
    • 符号

    我知道单个集合的模式,即 [a-z] , [A-Z] , \d _|[^\w] (我答对了,不是吗?).

    但是如何组合它们以确保字符串以任何顺序包含所有这些内容呢?

    3 回复  |  直到 6 年前
        1
  •  291
  •   Community CDub    6 年前

    如果需要一个regex,请尝试:

    (?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)
    

    简短解释:

    (?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
    (?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
    (?=.*\d)           // use positive look ahead to see if at least one digit exists
    (?=.*\W])        // use positive look ahead to see if at least one non-word character exists
    

    我同意SilentGhost, \W 可能有点宽。我将用如下字符集替换它: [-+_!@#$%^&*.,?] (当然可以添加更多!)

        2
  •  10
  •   Juan Furattini    7 年前

    巴特·基尔斯,你的雷鬼有几个问题。最好的方法是:

    (.*[a-z].*)       // For lower cases
    (.*[A-Z].*)       // For upper cases
    (.*\d.*)          // For digits
    

    这样,无论是在开始、结束还是在中间,你都在搜索。在你的“有”中,我有很多复杂密码的问题。

        3
  •  5
  •   SilentGhost    15 年前

    您可以分别匹配这三个组,并确保它们都存在。也, [^\w] 似乎有点太宽泛了,但如果你想换的话,你可以换成 \W .