开发者

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 wi开发者_StackOverflow社区thout 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜