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

时间:2018-03-09 05:45:58

标签: ruby-on-rails regex validation

我找到了遵守规则的正则表达式。

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

这是我的正则表达式:

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

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

1 个答案:

答案 0 :(得分: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:我还没有测试过。如果需要,我可以稍后进行测试和更新。

相关问题