I have an input, which can have different structure. I would like to test few patterns and get corresponding matching parts in each case without repeating the regular expressions. For example:
a = "hello123"
case a
when /^([0-9]+)([a-z]+)$/
# how to get matching values?
when /^([a-z]+)([0-9]+)$/
# how to get matching values?
else
end
It is a very simple example, and my code is a bit more complex.
Use
$~Will print MatchData object. (MatchData is the type of the special variable $~, and is the type of the object returned by Regexp#match and Regexp#last_match. It encapsulates all the results of a pattern match, results normally accessed through the special variables $&, $’, $`, $1, $2, (more about special vars) and so on. Matchdata is also known as MatchingData.)
http://ruby-doc.org/core/classes/Regexp.html#M001202