2011-10-17 28 views
1
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

是否有您要使用特定的原因正則表達式?我會使用一種方法。 – 2011-10-17 12:17:50

+0

沒有具體原因。這正是我開始的。我想這到了一個方法更重要的地步。既然如此,你將如何構建這個方法呢? – Trip 2011-10-17 12:19:15

回答

1

是不是很容易檢查對所有3!有效的排列?

編輯:

但要接受你的挑戰: (?:1(?!\d*1)|2(?!\d*2)|3(?!\d*3)){3}

它使用negative lookaheads,以確保數字採摘一次。

編輯:

Checked with rubular.com

1

您可能會將字符串分解爲3個數字。 a,b和c。

那麼你有很多方法來檢查。例如

分鐘VAL == 1和max == 3和sum = 6

把3爲一組(我希望紅寶石具有一組集合類型),該組的大小應爲3

等。

正則表達式可能不是解決這個問題的最佳工具。

1

正如其他人所說,最好使用方法或其他方法檢查唯一性。但是,如果你有充分的理由來使用正則表達式,則正則表達式將是這個樣子

^(\d)\s*(?!\1)(\d)\s*(?!\1|\2)(\d)$ 

它使用在各個手指負先行通過檢查aginst已拍攝組來驗證重複。如果你只檢查1,2和3,那麼你可以使用這個

^([123])\s*(?!\1)([123])\s*(?!\1|\2)([123])$ 
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) 
"