tags:

views:

29

answers:

2

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.

+3  A: 

Use $~

a = "hello123"
case a
when /^([0-9]+)([a-z]+)$/
  print $~
when /^([a-z]+)([0-9]+)$/
  print $~
else
end

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

Draco Ater
+2  A: 
a = "hello123"
case a
when /^([0-9]+)([a-z]+)$/
  # how to get matching values?
  puts [$~, $1, $2]
when /^([a-z]+)([0-9]+)$/
  print "regex 2 matched "
  p [$1, $2]                    # => ["hello", "123"]
  p $~.to_a                     # => ["hello123", "hello", "123"]
else
end
Gishu
Thank you, Gishu
Andrey