How can one get a list of matches in a string from multiple different Regexps, and have these matches ordered relatively by their position in the string?
The string can contain multiple matches from the same Regexp.
Based on sepp2k’s answer, here’s the solution I implemented (simplified example):
test_data = "
a_word
another_word
23445
12432423
third_word
"
regexps = /(?<word>[a-zA-Z_]+)/, /(?<number>[\d]+)/
words = regexps.map{|re| re.names}.flatten!
matches = []
test_data.scan(Regexp.union(regexps)) do
words.each do |word|
m = Regexp.last_match
matches << {word => m.to_s} if m[word]
end
end
p matches
This outputs:
[{"word"=>"a_word"}, {"word"=>"another_word"}, {"number"=>"23445"}, {"number"=>"12432423"}, {"word"=>"third_word"}]
You can use
Regexp.unionto turn all the regexps into one regexp and then useString#scanto find all matches. The array returned byscanwill be ordered by the position of the match.