首页 文章

RegEx包含字母,数字和特殊字符的组合

提问于
浏览
0

我找到了一个符合规则的正则表达式 .

验收标准:密码必须包含字母,数字和至少一个特殊字符的组合

这是我的正则表达式:

validates :password, presence: true,
format: { with: ^(?=[a-zA-Z0-9]*$)([^A-Za-z0-9])}

我在正则表达式方面并不是那么出色,所以非常感谢任何帮助!

1 回答

  • 2

    您可以使用以下RegEx模式

    /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,}$/
    

    让我们来看看它在做什么:

    (?=.*\d) shows that the string should contain atleast one integer.
    (?=.*([a-z]|[A-Z])) shows that the string should contain atleast one alphabet either from downcase or upcase.
    ([\x20-\x7E]) shows that string can have special characters of ascii values 20 to 7E.
    {8,} shows that string should be minimum of 8 characters long. While you have not mentioned it should be at least 8 characters long but it is good to have.
    

    如果你不确定ASCII值,你可以谷歌它或你可以使用以下代码:

    /^(?=.*\d)(?=.*([a-z]|[A-Z]))(?=.*[@#$%^&+=]){8,}$/
    

    正如评论中所建议的,更好的方法是:

    /\A(?=.*\d)(?=.*([a-z]))(?=.*[@#$%^&+=]){8,}\z/i
    

    这里:

    \A represents beginning of string.
    \z represents end of string.
    /i represents case in-sensitive mode.
    

    P.S:我还没有测试过 . 如果需要,我可以稍后进行测试和更新 .

相关问题