在Ruby的情况下,将Named Captures与regex匹配一起使用...何时? [英] Using Named Captures with regex match in Ruby's case...when?
本文介绍了在Ruby的情况下,将Named Captures与regex匹配一起使用...何时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用命名捕获来解析用户输入以提高可读性。
I want to parse user input using named captures for readability.
当他们键入命令时,我想捕获一些参数并传递它们。我在案例陈述中使用RegExps,因此无法分配 /pattern/.named_captures
的返回值。
When they type a command I want to capture some params and pass them. I'm using RegExps in a case statement and thus I can't assign the return of /pattern/.named_captures
.
这就是我想做的(例如):
Here is what I would like to be able to do (for example):
while command != "quit"
print "Command: "
command = gets.chomp
case command
when /load (?<filename>\w+)/
load(filename)
end
end
推荐答案
<当使用这种语法时,strong>命名捕获设置局部变量。
regex-literal =~ string
未设置其他语法。 #参见 rdoc(re.c)
Dosen't set in other syntax. # See rdoc(re.c)
regex-variable =~ string
string =~ regex
regex.match(string)
case string
when regex
else
end
我也喜欢命名捕获,但我不喜欢喜欢这种行为。
现在,我们必须使用$〜大小写语法。
I like named captures too, but I don't like this behavior. Now, we have to use $~ in case syntax.
case string
when /(?<name>.)/
$~[:name]
else
end
这篇关于在Ruby的情况下,将Named Captures与regex匹配一起使用...何时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文