2012-03-24 264 views
1

的範圍之前我有2個字符串:Ruby的正則表達式匹配的字符串與數字

I have 4 cars in my house 
I have 14 cars in my house 

我們如何使用紅寶石(1.9.3)的正則表達式來檢查只有1到10輛匹配?

例:

I have 1 car in my house # => match 
I have 4 cars in my house # => match 
I have 10 cars in my house # => match 
I have 14 cars in my house # => should not match 
I have 100 cars in my house # => should not match 

此外,我們該如何匹配(即2輛)針對任何字符串?所以如果目標字符串包含'22輛汽車',那麼它不應該匹配。

例:

some other string before 2 cars some other string after # => match 
some other string before 22 cars some other string after # => should not match  
+2

'/我有(1輛車| [2-9]車| 10輛車)在我家/'? – Howard 2012-03-24 16:46:56

+1

你的車不應該在你的車庫? :D霍華德提供了正確的答案。我第一次錯過了單數形式。 – alfa 2012-03-24 16:51:00

回答

1

正則表達式:/I have (?:1 car|[2-9] cars|10 cars) in my house/

您可以在http://rubular.com/

的嘗試interatively(?:XXX),使括號非獲取的陳述here

+0

完美地工作,謝謝大家!其實,我的問題是我有一個字符串(即2輛車),我想檢查它是否匹配任何字符串包含'2輛車'。所以在這種情況下,如果目標字符串包含'22輛汽車',那麼它不應該匹配。 – 2012-03-26 03:06:42

+0

使用*可匹配汽車數量前後的任何字符串。 – alfa 2012-03-26 07:56:01

+0

這仍然匹配字符串「我家有22輛汽車」。 – 2012-03-26 09:15:32

1

使用該正則表達式:/I have ([1-9]|10) cars? in my house./

[1-9]創建一個範圍的1,2,3,4,5,6,7,8,9和管道字符充當or以允許10.括號是一個捕獲組。汽車尾部的's'後面的問號意味着「零個或一個前面的字符」,因此匹配'汽車'和'汽車'。希望這有助於!

+0

這個解決方案比我的更簡單。它的缺點是「我家有10輛車。」或「我家有一輛車。」比賽。列出的用例已足夠,但我認爲這不是Hoang Nghiem所期望的。 ;)Btw:。匹配任何字符。它應該是 \。 – alfa 2012-03-24 17:02:10

+0

這是真的 - 好趕上!圓括號的好處是不捕獲的,但是呢? – 2012-03-24 17:04:04

+0

如果您只想知道整句是否匹配,並且不在意數字,您應該這樣做。也許你想在後面的正則表達式中捕獲其他東西,並且不想與索引混淆。 – alfa 2012-03-24 17:08:18