[英]Is there a built in api to extract a pattern (as many times as possible) from a string?
我想使用ruby 2.1尽可能多地从字符串中提取模式。 String#slice!
看起来很近,但只提取第一个匹配项。 要解决此问题,我编写了以下内容,但感觉很笨拙:
string = "ababab"
pattern = /a/
matches = []
# clunky
loop do
m = string.slice!(pattern) || break
matches << m
end
#=> matches == ["a", "a", "a"]
#=> string == "bbb"
现在,我可以使用自己的#extract!
扩展String
类#extract!
方法,或为此创建一个辅助对象,但是我觉得这种情况很常见,我只是缺少标准API的一部分,或者缺少一种更特殊的方式来做到这一点。
有没有更短的写方法?
您可以将一个块传递给gsub
:
string = "ababab"
pattern = /a/
matches = []
string.gsub!(pattern) { |s| matches << s ; '' }
string #=> "bbb"
matches #=> ["a", "a", "a"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.