Sunday, 16 July 2017

regex - How do I get the match data for all occurrences of a Ruby regular expression in a string?



I need the MatchData for each occurrence of a regular expression in a string. This is different than the scan method suggested in Match All Occurrences of a Regex, since that only gives me an array of strings (I need the full MatchData, to get begin and end information, etc).




input = "abc12def34ghijklmno567pqrs"
numbers = /\d+/

numbers.match input # # (only the first match)
input.scan numbers # ["12", "34", "567"] (all matches, but only the strings)


I suspect there is some method that I've overlooked. Suggestions?


Answer




You want



"abc12def34ghijklmno567pqrs".to_enum(:scan, /\d+/).map { Regexp.last_match }


which gives you



[#, #, #] 



The "trick" is, as you see, to build an enumerator in order to get each last_match.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...