在 Ruby 的情况下使用带有正则表达式匹配的命名捕获......什么时候? [英] Using Named Captures with regex match in Ruby's case...when?

查看:22
本文介绍了在 Ruby 的情况下使用带有正则表达式匹配的命名捕获......什么时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了便于阅读,我想使用命名捕获来解析用户输入.

I want to parse user input using named captures for readability.

当他们输入命令时,我想捕获一些参数并传递它们.我在 case 语句中使用 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

推荐答案

named captures设置局部变量时使用这种语法.

named captures set local variables when this syntax.

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

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

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 的情况下使用带有正则表达式匹配的命名捕获......什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆