p.matsinopoulos
p.matsinopoulos

Reputation: 7810

How to iterate over the matched groups of a regular expression

I have the following case that does not work the way I expect, and, I am doing something wrong, but I cannot find out what that is. The script matches the four letter words within a sentence. I want to find a way to iterate over the matched groups.

x = "This is a statement with four letter words like this"
result = x.match /(\b\w{4}\b)/
=> #<MatchData "This" 1:"This"> 

Unfortunately, $1 contains "This", but this is all I get. $2 should contain "with" but it is nil. What am I doing wrong? Why is $2 nil? Why is $n with n>=2 nil?

Upvotes: 4

Views: 1867

Answers (1)

undur_gongor
undur_gongor

Reputation: 15954

This is because your regexp matches just once and contains just one capture group.

You probably want:

x.scan /\b\w{4}\b/

which will give you an array of all matches.

$1, $2 ... are set to the groups in a single match of the regexp, e.g.

x.match(/(\b\w{4}\b).*(\b\w{4}\b)/)

sets $1 to 'This' and $2 to 'this'.

The groups can also be accessed through $~[1], $~[2], ... or Regexp.last_match[1] ...

Upvotes: 5

Related Questions