Reputation: 18149
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
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