我目前正在尝试将一个字符串转换为多个变量。示例字符串:
ryan_string = "RyanOnRails: This is a test"
我已将其与此正则表达式匹配,分为 3 组:
ryan_group = ryan_string.scan(/(^.*)(:)(.*)/i)
现在要访问每个组,我必须执行如下操作:
ryan_group[0][0] (first group) RyanOnRails
ryan_group[0][1] (second group) :
ryan_group[0][2] (third group) This is a test
这看起来很荒谬,感觉我做错了什么。我希望能够做这样的事情:
g1, g2, g3 = ryan_string.scan(/(^.*)(:)(.*)/i)
这可能吗?还是有比我现在做的更好的方法?
最佳答案
您不希望为此扫描
,因为它毫无意义。您可以使用 String#match
返回一个 MatchData
对象,然后您可以调用 #captures
返回一个捕获数组。像这样:
#!/usr/bin/env ruby
string = "RyanOnRails: This is a test"
one, two, three = string.match(/(^.*)(:)(.*)/i).captures
p one #=> "RyanOnRails"
p two #=> ":"
p three #=> " This is a test"
请注意,如果未找到匹配项,String#match
将返回 nil,因此这样的方法可能会更好:
if match = string.match(/(^.*)(:)(.*)/i)
one, two, three = match.captures
end
尽管 scan
对此没有什么意义。它仍然可以完成工作,您只需要先展平返回的数组即可。 一、二、三 = string.scan(/(^.*)(:)(.*)/i).flatten
关于Ruby 正则表达式组匹配,在 1 行上分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9303984/