2010-02-08 103 views

回答

30

可以使用String類的=~法正則表達式/\d/作爲參數。

下面是一個例子:

s = 'abc123' 

if s =~ /\d/   # Calling String's =~ method. 
    puts "The String #{s} has a number in it." 
else 
    puts "The String #{s} does not have a number in it." 
end 
5
if /\d/.match(theStringImChecking) then 
    #yep, there's a number in the string 
end 
7

另外,不使用正則表達式:

def has_digits?(str) 
    str.count("0-9") > 0 
end 
+2

如果您忽略編譯正則表達式的開銷(如果測試在大循環中完成或者要檢查的字符串很長時,這是公平的),那麼這可能效率較低。對於退化情況,您的解決方案必須遍歷整個字符串,而一旦找到數字,正確的正則表達式就會停止。 – 2010-02-09 15:30:23

+0

雖然這可能不是最有效的,但它是非常可讀的,對某些情況可能會更好。 – 2014-04-04 09:29:05

2

而不是使用類似 「S =〜/ \ d /」,我去的短小號[/ \ d /]返回一個未命中的錯誤(在條件測試中AKA錯誤)或命中的索引(在有條件測試中AKA爲真)。如果你需要使用實際的值,那麼它應該都是相同的,並且主要是程序員的選擇。

1
!s[/\d/].nil? 

可以是獨立的功能 -

def has_digits?(s) 
    return !s[/\d/].nil? 
end 

或...將其添加到String類使得它更方便 -

class String 
    def has_digits? 
    return !self[/\d/].nil? 
    end 
end 
相關問題