简体   繁体   中英

How can I test regexp and fetch matching parts in Ruby?

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 $~

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM