Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through each "match" (Ruby regex)

Tags:

regex

ruby

Okay, I can find a Regex match in a string, and do some captures. Now, what if my string has many matches? Let's say my code finds out the number inside parenthesis in a string. The code will find the number in a string like

(5)

But what if the string is

(5) (6) (7)

I need a way to iterate through these three elements. I've seen tutorials, but they seem to only talk about one-time matches...

like image 651
Voldemort Avatar asked May 27 '11 01:05

Voldemort


2 Answers

If I understand correctly, you could use the String#scan method. See documentation here.

like image 117
dee-see Avatar answered Sep 20 '22 19:09

dee-see


String#scan can be used to find all matches of a given regex:

"(5) (6) (7)".scan(/\(\d+\)/) { |match| puts "Found: #{match}" } # Prints: Found: (5) Found: (6) Found: (7) 

You can use positive look behind (?<=) and look ahead (?=) to exclude the parenthesis from your results:

"(5) (6) (7)".scan(/(?<=[(])\d+(?=\))/) { |match| puts "Found: #{match}" } # Prints: Found: 5 Found: 6 Found: 7 

If you don't pass a block to scan, it returns an array with all matches:

"(5) (6) (7)".scan(/(?<=[(])\d+(?=\))/) => ["5", "6", "7"] 
like image 33
Christopher Oezbek Avatar answered Sep 18 '22 19:09

Christopher Oezbek