ruby-on-rails - Ruby 正则表达式不工作

标签 ruby-on-rails ruby regex

应允许以下用户名:

Foo-Bar
Foobar
Fooo_123
Foob123_1
Foo-bar-123

不允许使用以下用户名:

_Foobar_
F-o-o-b-a-r
-Foobar-
_-Foobar-_

意思是:字符串允许长度为 3 到 20 个字符。每三个字符只允许有一个破折号或下划线。不是在开始,也不是在结束。您最多只能使用 2 个破折号或下划线,最多 3 个数字,但最少 3 个字母。

这是我到目前为止所做的正则表达式,但我已经无法在前端和末尾使用破折号了:

/^[^\-_][a-zA-Z0-9]{3,20}[^\-_]$/

提前致谢!

最佳答案

这对于单个正则表达式来说可能太复杂了,如果你能做一个,它会过于不可读和复杂。我建议你简单地进行多次检查;例如:

valid = str.length >= 3 && str.length <= 20        # or str.length.between? 3, 20
        && str =~ /^[^-_]+([-_][^-_]{3,})*[-_]?[^-_]+$/
        && str.count '-_' <= 2
        && str.count '0-9' <= 3
        && str.count 'A-Za-z' >= 3

正则表达式的解释:

/
  [^-_]+      # any amount of non-dashes/underscores (so it can't start with one)
  (
    [-_]      # a dash/underscore
    [^-_]{3,} # 3 or more non-dashes/underscores
  )
  *           # zero or more times
  [-_]?       # an optional dash/underscore
  [^-_]+      # any amount of non-dashes/underscores (so it can't end with one)
/x

关于ruby-on-rails - Ruby 正则表达式不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21741818/

相关文章:

ruby - ruby 选项解析应该在哪里?

Java:如何分割字符串而忽略其他部分

ruby-on-rails - application.html.erb 其中第 6 行引发 : TypeError: Ruby on rails

ruby-on-rails - 从 MongoDB 1.8 升级到 2.4 时如何解决 MongoDB/PCRE “symbol lookup error”

ruby-on-rails - 如何在 Rails 中的 Web 请求中对长进程进行子线程化

javascript - 按最长公共(public)起始子串对字符串进行分组

JavaScript 正则表达式反向引用从单个捕获组(多个组)返回一组匹配项

ruby-on-rails - Rails 6 rake Assets :precompile failing with Docker on AWS due to missing Master Key Env variable

javascript - 在 Node.js 应用程序和 Rails 应用程序之间共享 session

ruby-on-rails - Rails 4 attr_readonly 更新