1

I am working through a book and it gives this example

x = "This is a test".match(/(\w+) (\w+)/)

We are looking at the parentheses and being able to access what is passed separately.

When I put the expression above into my IRB I get:

MatchData "This is" 1:"This" 2:"is">

Why doesn't this also include a and Test?

Would I have to include .match(/(\w+) (\w+) (\w+) (\w+)/) ?

4

1 回答 1

3

'match' 方法与全局正则表达式不匹配。它只返回第一场比赛。您可以使用“扫描”方法而不是“匹配”,它应该返回一个包含所有正则表达式匹配的数组。

[~]$ irb
1.8.7-p371 :001 > x = "This is a test".match(/(\w+) (\w+)/)
 => #<MatchData "This is" 1:"This" 2:"is">
1.8.7-p371 :002 > x = "This is a test".scan(/(\w+) (\w+)/)
 => [["This", "is"], ["a", "test"]]
于 2013-08-13T16:41:49.613 回答