Q
获取红宝石
12
A
回答
19
试试这个:
res = []
"abab".scan(/a/) do |c|
res << [c, $~.offset(0)[0]]
end
res.inspect # => [["a", 0], ["a", 2]]
1
让我吃惊,没有类似String#scan
这将返回MatchData
对象的数组,类似于String#match
任何方法。所以,如果你喜欢猴子打补丁,你可以与托德的解决方案结合本(Enumerator
在1.9中引入):
class Regexp
def scan str
Enumerator.new do |y|
str.scan(self) do
y << Regexp.last_match
end
end
end
end
#=> nil
/a/.scan('abab').map{|m| m.offset(0)[0]}
#=> [0, 2]
+0
NoMethodError:undefined method'scan'for – Andy 2016-01-07 12:49:43
6
有一个疑难杂症看出来这里,这取决于你所期望的行为。
如果您在"dadad"
搜索/dad/
你只能得到[["dad",0]]
因为scan
进步到每场比赛结束的时候找到一个(这是我错了)。
我想出了这样的选择:
def scan_str(str, pattern)
res = []
(0..str.length).each do |i|
res << [Regexp.last_match.to_s, i] if str[i..-1] =~ /^#{pattern}/
end
res
end
如果你想你也可以从标准库中做类似的事情与StringScanner,它可能是长字符串更快。
4
非常相似,@jim说,并适用于较长的串好一点:
def matches str, pattern
arr = []
while (str && (m = str.match pattern))
offset = m.offset(0).first
arr << offset + (arr[-1] ? arr[-1] + 1 : 0)
str = str[(offset + 1)..-1]
end
arr
end
嗨 - 抱歉大量垃圾邮件,但http://area51.stackexchange.com/proposals/74083/korean-语言可以使用你,如果你不在那里! – 2016-05-23 18:39:16