Multiple Match in Ruby
· 1 min read
When somebody needs to find all occerences of a pattern in a string, she usually
does either
scan
or repeatitive
match
calls. I was unable to google a quick solution
of getting all the
MatchData
instances. Even
StackOverflow provides
a strange answers on a topic, like that one below:
str.to_enum(:scan, /PATTERN/).map { Regexp.last_match }
Actually, the
owls are easier than they seem
. All we
need is to use one of a cryptic
$
ruby globals
:
input = "abc12def34ghijklmno567pqrs"
numbers = /\d+/
input.gsub(numbers) { |m| p $~ }
prints all the
MatchData
s:
# โ <MatchData "12">
# โ <MatchData "34">
# โ <MatchData "567">
Voilร .