給出字符串:簡單的正則表達式匹配工作在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}
。
我在做什麼錯?
謝謝,這是有效的。但是爲什麼正則表達式不會返回匹配,你知道嗎? – Zabba
@Zabba,'String#match'使用'Regexp#match'返回'MatchObject';代表一場比賽。我不知道方法設計決策歷史。 – falsetru
啊,我明白了。所以使正則表達式'/(%{.*}).*(%{.*})/'返回匹配。謝謝! – Zabba