Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Regex-tut] Groups Redux: Capturing Groups Intro
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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.
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: