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
相关问题
- 1. 获取红宝石
- 2. 获取红宝石
- 3. 红宝石获取价值
- 4. 提取红宝石
- 5. 红宝石宝石mongo取决于bson1.10.12
- 6. 获取宝石的版本红宝石内
- 7. 如何获取是红宝石宝石的代码?
- 8. 从外部的红宝石安装获取宝石版本
- 9. 如何:获取通过PayPal红宝石宝石
- 10. 红宝石获取'输入密钥'
- 11. 使用红宝石“获取”块
- 12. 红宝石:获取值,如果真或
- 13. 获取参数里面的红宝石
- 14. 红宝石 - 获取鼠标坐标
- 15. 红宝石:获取光纤父母
- 16. 红宝石 - “获取”增加换行符
- 17. 镜像终端与获取红宝石
- 18. 红宝石散列在红宝石
- 19. 红宝石宝石文档
- 20. 宝石安装红宝石
- 21. 调试宝石红宝石
- 22. 红宝石程序宝石
- 23. 错误红宝石宝石
- 24. Twitter的红宝石宝石
- 25. 卸载红宝石宝石
- 26. 红宝石宝石 - LoadError
- 27. 红宝石宝石LoadError
- 28. 安装红宝石宝石
- 29. 如何获得红宝石2.0模块#prepend在红宝石1.8?
- 30. 红宝石:捕获输出
嗨 - 抱歉大量垃圾邮件,但http://area51.stackexchange.com/proposals/74083/korean-语言可以使用你,如果你不在那里! – 2016-05-23 18:39:16