October 2006
Intermediate to advanced
888 pages
16h 55m
English
Each parenthesized piece of a regular expression will be a submatch of its own. These are numbered and can be referenced by these numbers in more than one way. Let’s examine the more traditional “ugly” ways first.
The special global variables $1, $2, and so on, can be used to reference matches:
str = "a123b45c678" if /(a\d+)(b\d+)(c\d+)/ =~ str puts "Matches are: '#$1', '#$2', '#$3'" # Prints: Matches are: 'a123', 'b45', 'c768' end
Within a substitution such as sub or gsub, these variables cannot be used:
str = "a123b45c678" str.sub(/(a\d+)(b\d+)(c\d+)/, "1st=#$1, 2nd=#$2, 3rd=#$3") # "1st=, 2nd=, 3rd="
Why didn’t this work? Because the arguments to sub are evaluated before sub is called. This code is equivalent: ...
Read now
Unlock full access