Computer Science Canada

[Regex-tut] Groups Redux: Capturing Groups Intro

Author:  wtd [ Sat Nov 13, 2004 10:35 pm ]
Post subject:  [Regex-tut] Groups Redux: Capturing Groups Intro

Recap

Earlier I described that you can use sets of parentheses to create groups. For instance:

code:
/ ( Hello | Toodles ) /x


Matches either:

code:
"Hello"


Or:

code:
"Toodles"


But what did it match?

So I can say:

code:
# 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:

code:
( Hello | Toodles )


Get put into the variable $1.

So, to output what we captured:

code:
# 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.


: