Ruby Regex: Get Capture Index

I saw this question and answered for javascript regex and the answer was long and very ugly. Curious if someone has a cleaner way to implement in ruby.

Here is what I am trying to achieve:

Test string: "foo bar baz"
Regex: /.*(foo).*(bar).*/
Expected Return: [[0,2],[4,6]]

So, my goal is to be able to run a method running in the test string and regular expression, which will return the indices in which each capture group will correspond. I have included both the start and end indexes of the capture groups in the expected return. I will work on it and add my own potential solutions here along the way too. And of course, if there is a way other than regex that is cleaner / easier for this, this is a good answer too.

+4
source share
2 answers

Something like this should work for the total number of matches.

 def match_indexes(string, regex) matches = string.match(regex) (1...matches.length).map do |index| [matches.begin(index), matches.end(index) - 1] end end string = "foo bar baz" match_indexes(string, /.*(foo).*/) match_indexes(string, /.*(foo).*(bar).*/) match_indexes(string, /.*(foo).*(bar).*(baz).*/) # => [[0, 2]] # => [[0, 2], [4, 6]] # => [[0, 2], [4, 6], [8, 10]] 

You can take a look at the (some weird) MatchData class for how this works. http://www.ruby-doc.org/core-1.9.3/MatchData.html

+5
source
 m = "foo bar baz".match(/.*(foo).*(bar).*/) [1, 2].map{|i| [m.begin(i), m.end(i) - 1]} # => [[0, 2], [4, 6]] 
+5
source

Source: https://habr.com/ru/post/1492144/


All Articles