应允许以下用户名:
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/