简单的正则表达式匹配适用于rubular但不适用于IRB

时间:2013-10-19 06:46:29

标签: ruby regex

给出字符串:

"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}

我做错了什么?

3 个答案:

答案 0 :(得分:4)

使用String#scan方法:

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

使用非捕获组:

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

更新实际上,不需要分组。

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

这是供将来参考的,因为这是Google上出现的第一个问题。

我刚刚遇到这个问题,我的测试工作在Rubular上但是当我运行我的代码时他们没有工作。

我正在测试类似/^<regex-goes-here>$/

的内容

结果我正在测试的正则表达式以回车符\n\r结束,但我没有将它们复制到Rubular,所以当然它们不匹配。

希望这会有所帮助。