validates_format_of :order_of_importance, :on => :create, :with => /^[1-3]{3}$/,
:message => "Order of Importance must have 3 Digits"
现在我已经验证使用的数字是1, 2, 3
,但我想也确保不仅使用这些数字,而且每个数字仅用于一次。
例如:
应该是工作号码
2 3 1
1 3 2
1 2 3
不应该是有效的数字:
1 1 2
2 2 1
3 3 3
答案 0 :(得分:2)
if subject =~ /\A(?:\A(?=[1-3]{3}\Z)(\d)(?!\1)(\d)(?!(?:\1|\2))\d\Z)\Z/
# Successful match
else
# Match attempt failed
end
这将匹配一个字符串,其中包含1-3个范围内的3个数字,没有重复的数字。
细分:
"
^ # Assert position at the beginning of the string
(?= # Assert that the regex below can be matched, starting at this position (positive lookahead)
[1-3] # Match a single character in the range between “1” and “3”
{3} # Exactly 3 times
\$ # Assert position at the end of the string (or before the line break at the end of the string, if any)
)
( # Match the regular expression below and capture its match into backreference number 1
\\d # Match a single digit 0..9
)
(?! # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
\\1 # Match the same text as most recently matched by capturing group number 1
)
( # Match the regular expression below and capture its match into backreference number 2
\\d # Match a single digit 0..9
)
(?! # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
\\1 # Match the same text as most recently matched by capturing group number 1
| # Or match regular expression number 2 below (the entire group fails if this one fails to match)
\\2 # Match the same text as most recently matched by capturing group number 2
)
)
\\d # Match a single digit 0..9
\$ # Assert position at the end of the string (or before the line break at the end of the string, if any)
"
答案 1 :(得分:1)
检查所有3个是不是更容易!有效的排列?
编辑:
但要接受挑战:
(?:1(?!\d*1)|2(?!\d*2)|3(?!\d*3)){3}
它使用negative lookaheads来确保只挑选一次数字。
编辑:
答案 2 :(得分:1)
你可以将字符串分成3个数字。 a,b和c。
然后你有很多方法可以检查。 e.g。
min val == 1 and max == 3 and sum = 6
将3放入一组(我希望ruby具有set集合类型),集合的大小应为3。
等。
正则表达式可能不是解决此问题的最佳工具。
答案 3 :(得分:1)
正如其他人已经说过的,最好使用方法或其他方法来检查唯一性。但是如果你有理由使用正则表达式,那么正则表达式看起来就像这样
^(\d)\s*(?!\1)(\d)\s*(?!\1|\2)(\d)$
它在每个数字上使用否定前瞻,通过检查已捕获的组来确认重复。如果你只需要检查1,2和3,那么你可以使用这个
^([123])\s*(?!\1)([123])\s*(?!\1|\2)([123])$
答案 4 :(得分:0)
我强烈推荐[在线正则表达式构建器] [1]
[1]:http://www.gskinner.com/RegExr/以避免怀疑