[英]Ruby Regexp Not Working
應允許以下用戶名:
Foo-Bar
Foobar
Fooo_123
Foob123_1
Foo-bar-123
不應允許以下用戶名:
_Foobar_
F-o-o-b-a-r
-Foobar-
_-Foobar-_
這意味着:字符串允許長度為3到20個字符。 每三個字符只允許一個短划線或下划線。 不是在開始,不是在結束。 您最多只能使用2個短划線或下划線,最多3個數字,但最少3個字母。
這是我到目前為止所做的Regexp,但是我已經失敗了允許前端和后端的破折號:
/^[^\-_][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
我建議你從/^(?![-_])[-_a-zA-Z0-9]{3,20}(?<![-_])$/
,這將允許你所有的確定-usernames只有一個不好(詳見rubular )。 然后繼續Doorknob建議並對頻率施加限制 - 並使用_,......
如何 - 和_在開始和結束被抑制?
(?![-_])
確保下一個字符既不是 - 也不是_ (?<![-_])
- _ (?<![-_])
確保前一個字符既不是_也不_
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.