Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find both pattern and position of multiple regex matches in Ruby

Tags:

regex

ruby

This should be an easy question but I can't find anything about it.

Given a regular expression in Ruby, for every match I need to retrieve the matched patterns $1, $2, but I also need the matching position.

I know that the =~ operator gives me the position of the first match, while string.scan(/regex/) gives me all matching patterns. If possible I need to have both results in the same step.

like image 985
Emyl Avatar asked Nov 27 '12 17:11

Emyl


2 Answers

MatchData

string.scan(regex) do
  $1           # Pattern at first position
  $2           # Pattern at second position
  $~.offset(1) # Starting and ending position of $1
  $~.offset(2) # Starting and ending position of $2
end
like image 127
sawa Avatar answered Nov 19 '22 17:11

sawa


You can access match data within scan like this:

"abcdefghij".scan(/\w/) {p $~}
like image 24
davidrac Avatar answered Nov 19 '22 18:11

davidrac