我目前正在尝试将一个字符串重新编译成多个变量。示例字符串:
ryan_string = "RyanOnRails: This is a test"
我将其与下面的regexp进行了匹配,其中包含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)
这个是可能的吗?或者有比我做的更好的方法吗?
发布于 2012-02-16 09:00:13
你不需要scan
来做这件事,因为它没什么意义。您可以使用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
对此并没有多大意义。它仍然可以做这项工作,你只需要首先扁平化返回的数组。one, two, three = string.scan(/(^.*)(:)(.*)/i).flatten
发布于 2012-02-16 08:59:55
您可以使用Match或=~,这将为您提供单个匹配,并且您可以以相同的方式访问匹配数据,或者只使用特殊的匹配变量$1、$2、$3
类似于:
if ryan_string =~ /(^.*)(:)(.*)/i
first = $1
third = $3
end
发布于 2014-01-29 01:23:00
您可以命名捕获的匹配项
string = "RyanOnRails: This is a test"
/(?<one>^.*)(?<two>:)(?<three>.*)/i =~ string
puts one, two, three
如果颠倒字符串和正则表达式的顺序,它将不起作用。
https://stackoverflow.com/questions/9303984
复制相似问题