gpt4 book ai didi

ruby - 在 Ruby 的情况下使用带正则表达式匹配的命名捕获……什么时候?

转载 作者:数据小太阳 更新时间:2023-10-29 06:41:02 26 4
gpt4 key购买 nike

我想使用命名捕获来解析用户输入以提高可读性。

当他们键入命令时,我想捕获一些参数并传递它们。我在 case 语句中使用 RegExp,因此无法分配 /pattern/.named_captures 的返回值。

这是我希望能够做的(例如):

while command != "quit"
print "Command: "
command = gets.chomp
case command
when /load (?<filename>\w+)/
load(filename)
end
end

最佳答案

named captures 在此语法时设置局部变量。

regex-literal =~ string

不要在其他语法中设置。 # 参见 rdoc(re.c)

regex-variable =~ string

string =~ regex

regex.match(string)

case string
when regex
else
end

我也喜欢命名捕获,但我不喜欢这种行为。现在,我们必须使用 $~ in case 语法。

case string
when /(?<name>.)/
$~[:name]
else
end

关于ruby - 在 Ruby 的情况下使用带正则表达式匹配的命名捕获……什么时候?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com