2011-10-11 46 views
0

我希望通過我的對象屬性對於不是罪魁禍首:如何爲整數的正則表達式掃描返回一個布爾值?

^[1-3]{3}$ 

什麼是用於掃描的正則表達式的整數的方法是什麼?

+0

你爲什麼不轉換爲字符串,字符串掃描整? – Bohdan

+0

@Bohdan,雖然沒有返回布爾值,所以我無法檢測到它是否工作。至少我不認爲我可以。 – Trip

+1

mm我不知道我是否能正確地取得所有東西,但是''1234'[/^[1-3] {3} $ /]'返回'nil',它是'false'和'「123」[/^[ 1-3] {3} $ /]'returns'「123」'這是'true'與你所需要的相似嗎? – Bohdan

回答

4

一些例子:

124.to_s.match(/^[1-3]{3}$/) 
=> nil 
123.to_s.match(/^[1-3]{3}$/) 
=>#<MatchData "123"> 

由於nil被視爲false,你有你的布爾值。

例:

"no yo" if 124.to_s.match(/^[1-3]{3}$/) 
=> nil 
"yo!" if 123.to_s.match(/^[1-3]{3}$/) 
=> "yo!" 
+0

感謝apeadiving – Trip

+0

不客而非Trip :) – apneadiving

1

您也可以使用下列操作之一:

def is_pure_integer?(i) 
    i.to_i.to_s == i.to_s 
end 

'132' =~ /^\d+$/ ? true : false

相關問題