regex - 使用正则表达式验证密码

标签 regex ruby-on-rails-3 validation

我正在开发一个需要根据以下标准验证密码的 Rails 3 应用程序:must be at least 6 characters and include one number and one letter.
这是我的正则表达式:

validates :password, :format => {:with => /^[([a-z]|[A-Z])0-9_-]{6,40}$/, message: "must be at least 6 characters and include one number and one letter."}

现在,如果我输入密码(例如:dogfood),它将通过。但我需要它做的是通过上述标准。

我不太擅长正则表达式,因此非常感谢任何和所有帮助!

最佳答案

使用前瞻断言:

/^(?=.*[a-zA-Z])(?=.*[0-9]).{6,}$/
  |             |          |
  |             |          |
  |             |          Ensure there are at least 6 characters.
  |             |
  |             Look ahead for an arbitrary string followed by a number.
  |                        
  Look ahead for an arbitrary string followed by a letter.

从技术上讲,在这种情况下,您不需要 anchor ,但使用它们是一个好习惯。

关于regex - 使用正则表达式验证密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992544/

相关文章:

php - 正则表达式跳过一个标签,如果它在另一个标签内

php正则表达式从字符串中提取多个匹配项

validation - 在 Spring Boot 中遇到有关验证器的问题

java 正则表达式 : finding a pattern of one character s follows by 5 digits range 0-9

java - 如何在java中使用正则表达式从单词末尾删除ing

ruby-on-rails - 创建 Rails 3 引擎时出现问题

ruby-on-rails - 分隔目录中的 Rails 邮件程序 View

ruby-on-rails - 对于存在的路由,为什么我会得到 'no route matches' ?

asp.net-mvc-3 - MVC3 Razor 局部 View 渲染不包括数据验证属性

Java泛型通配符运算符