Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 259
mahemoff Avatar asked Jan 23 '26 20:01

mahemoff


1 Answers

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"]
like image 98
Stefan Avatar answered Jan 25 '26 13:01

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!