Saturn
Saturn

Reputation: 18149

Iterate through each "match" (Ruby regex)

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...

Upvotes: 31

Views: 19964

Answers (2)

Christopher Oezbek
Christopher Oezbek

Reputation: 26433

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"]

Upvotes: 10

dee-see
dee-see

Reputation: 24078

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

Upvotes: 38

Related Questions