mahemoff mahemoff - 6 months ago 29
Ruby Question

Ruby: Find first N regex matches in a string (and stop scanning)

Wanting to scan a very long string for regex matches. Wondering what would be the most efficient way to find the first N regex's. e.g. Something like:

'abcabcabc'.scan /b/, limit: 2

would end successfully after 5 characters, if only scan supported a limit option.

(The string is several MB - a memoized data structure in memory - and this is a web request. Perf matters.)


Not that elegant, but you could use the block form:

str = 'abcabcabc'

result = []
str.scan(/b/) { |match| result << match; break if result.size >= 2 }
result #=> ["b", "b"]