简体   繁体   English

在Ruby的情况下使用带有正则表达式匹配的Named Captures何时……

[英]Using Named Captures with regex match in Ruby's case…when?

I want to parse user input using named captures for readability. 我想使用命名捕获来解析用户输入以提高可读性。

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 . 我在case语句中使用RegExps,因此无法分配/pattern/.named_captures的返回/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 set local variables when this syntax. 使用此语法时, named捕获设置的局部变量。

regex-literal =~ string

Dosen't set in other syntax. 未设置其他语法。 # See rdoc(re.c) #参见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

This is ugly but works for me in Ruby 1.9.3: 这很丑陋,但在Ruby 1.9.3中对我有用:

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

Alternatively you can use the English extension of $~ , $LAST_MATCH_INFO . 或者,您可以使用$~的英文扩展名$LAST_MATCH_INFO

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

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