如何使用正则表达式和反向引用编写 Ruby switch 语句(case...when)? [英] How to write a Ruby switch statement (case...when) with regex and backreferences?
问题描述
我知道我可以编写一个 Ruby case 语句来检查与正则表达式的匹配.但是,我想在返回语句中使用匹配数据.像这样的半伪代码:
I know that I can write a Ruby case statement to check a match against a regular expressions. However, I'd like to use the match data in my return statement. Something like this semi-pseudocode:
foo = "10/10/2011"
case foo
when /^([0-9][0-9])/
print "the month is #{match[1]}"
else
print "something else"
end
我怎样才能做到这一点?
How can I achieve that?
谢谢!
请注意:我知道我永远不会将 switch 语句用于上述简单情况,但这只是一个示例.实际上,我想要实现的是匹配可以用各种方式编写的日期的许多潜在正则表达式,然后相应地使用 Ruby 的 Date 类对其进行解析.
Just a note: I understand that I wouldn't ever use a switch statement for a simple case as above, but that is only one example. In reality, what I am trying to achieve is the matching of many potential regular expressions for a date that can be written in various ways, and then parsing it with Ruby's Date class accordingly.
推荐答案
对最新正则表达式匹配组的引用始终存储在 伪变量 $1
到 $9
:
The references to the latest regex matching groups are always stored in pseudo variables $1
to $9
:
case foo
when /^([0-9][0-9])/
print "the month is #{$1}"
else
print "something else"
end
您还可以使用 $LAST_MATCH_INFO
伪变量获取整个 MatchData
对象.这在使用命名捕获时很有用:
You can also use the $LAST_MATCH_INFO
pseudo variable to get at the whole MatchData
object. This can be useful when using named captures:
case foo
when /^(?<number>[0-9][0-9])/
print "the month is #{$LAST_MATCH_INFO['number']}"
else
print "something else"
end
这篇关于如何使用正则表达式和反向引用编写 Ruby switch 语句(case...when)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!