简体   繁体   English

如何在Ruby中测试正则表达式并获取匹配的部分?

[英]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对象。 (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.) (MatchData是特殊变量$〜的类型,是Regexp#match和Regexp#last_match返回的对象的类型。它封装了模式匹配的所有结果,通常通过特殊变量$&,$访问该结果',$`,$ 1,$ 2( 更多有关特殊变量的信息 ),依此类推。Matchdata也称为MatchingData。)

http://ruby-doc.org/core/classes/Regexp.html#M001202 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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