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...
If I understand correctly, you could use the String#scan
method. See documentation here.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With