2013-10-19 27 views
1

給出字符串:簡單的正則表達式匹配工作在rubular但不是在IRB

"hello %{one} there %{two} world" 

此代碼不起作用:

s = "hello %{one} there %{two} world" 
r = Regexp.new(/(%{.*?})+/) 
m = r.match(s) 
m[0] # => "%{one}" 
m[1] # => "%{one}" 
m[2] # => nil # I expected "%{two}" 

但在Rubular,同樣的正則表達式(%{.*?})作品,並返回%{one}%{two}

我在做什麼錯?

回答

4

使用String#scan方法:

'hello %{one} there %{two} world'.scan(/(%{.*?})/) 
# => [["%{one}"], ["%{two}"]] 

隨着非捕獲組:

'hello %{one} there %{two} world'.scan(/(?:%{.*?})/) 
# => ["%{one}", "%{two}"] 

UPDATE實際上,不需要分組。

'hello %{one} there %{two} world'.scan(/%{.*?}/) 
# => ["%{one}", "%{two}"] 
+0

謝謝,這是有效的。但是爲什麼正則表達式不會返回匹配,你知道嗎? – Zabba

+2

@Zabba,'String#match'使用'Regexp#match'返回'MatchObject';代表一場比賽。我不知道方法設計決策歷史。 – falsetru

+0

啊,我明白了。所以使正則表達式'/(%{.*}).*(%{.*})/'返回匹配。謝謝! – Zabba

1
'hello %{one} there %{two} world'.scan /%{[^}]*}/ 
#=> ["%{one}", "%{two}"] 
0

這是供將來參考,因爲這是在谷歌彈出的第一個問題。

我剛剛碰到這個問題,我的測試在Rubular上工作,但是當我運行我的代碼時,他們沒有工作。

我在測試類似/^<regex-goes-here>$/

原來我對在運輸結束了正則表達式測試線路,返回\n\r,但我不是將它們複製到Rubular等等,當然他們不會匹配。

希望這會有所幫助。

相關問題