mahemoff mahemoff - 1 year ago 92
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.)

Answer Source

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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download