Ruby String#scan等效于返回MatchData [英] Ruby String#scan equivalent to return MatchData
问题描述
如问题标题中所述,在Ruby字符串上是否有一种等效于 String#Scan ,而不是仅返回每个匹配项的列表,而是返回一个MatchData
s数组?例如:
As basically stated in the question title, is there a method on Ruby strings that is the equivalent to String#Scan but instead of returning just a list of each match, it would return an array of MatchData
s? For example:
# Matches a set of characters between underscore pairs
"foo _bar_ _baz_ hashbang".some_method(/_[^_]+_/) #=> [#<MatchData "_bar_"&rt, <MatchData "_baz_"&rt]
或者我能获得相同或相似结果的任何方式都会很好.我想这样做是为了找到Ruby字符串中字符串"的位置和范围,例如"goodbye
和"world"
位于'再见'残酷的'世界'"中.
Or any way I could get the same or similar result would be good. I would like to do this to find the positions and extents of "strings" within Ruby strings, e.g. "goodbye
and "world"
inside "'goodbye' cruel 'world'".
推荐答案
您可以通过利用pos参数rel ="nofollow noreferrer"> String#match
.像这样:
You could easily build your own by exploiting MatchData#end
and the pos
parameter of String#match
. Something like this:
def matches(s, re)
start_at = 0
matches = [ ]
while(m = s.match(re, start_at))
matches.push(m)
start_at = m.end(0)
end
matches
end
然后:
>> matches("foo _bar_ _baz_ hashbang", /_[^_]+_/)
=> [#<MatchData "_bar_">, #<MatchData "_baz_">]
>> matches("_a_b_c_", /_[^_]+_/)
=> [#<MatchData "_a_">, #<MatchData "_c_">]
>> matches("_a_b_c_", /_([^_]+)_/)
=> [#<MatchData "_a_" 1:"a">, #<MatchData "_c_" 1:"c">]
>> matches("pancakes", /_[^_]+_/)
=> []
如果您确实愿意,可以将其修补到String中.
You could monkey patch that into String if you really wanted to.
这篇关于Ruby String#scan等效于返回MatchData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!