
-----------------------------------
wtd
Sat Nov 13, 2004 10:35 pm

[Regex-tut] Groups Redux: Capturing Groups Intro
-----------------------------------
Recap

Earlier I described that you can use sets of parentheses to create groups.  For instance:

/ ( Hello | Toodles ) /x

Matches either:

"Hello"

Or:

"Toodles"

But what did it match?

So I can say:

# get input from the user
input = gets.chomp

# match
if input =~ / ( Hello | Toodles ) /x
   puts "Matched."
end

But I kinda want to know what I matched.

Capturing groups

Groups using parentheses are also known as "capturing groups".  This is because they serve another purpose.  They remember what they matched, or in other words, "capture" it.  What they matched gets put into a special set of global variables.

In the above case, if the input matches the regular expression, the results of:

( Hello | Toodles )

Get put into the variable $1.

So, to output what we captured:

# get input from the user
input = gets.chomp

# match
if input =~ / ( Hello | Toodles ) /x
   puts "Matched: #{$1}."
end

The numbering scheme continues as you would expect.
