serengeti12
serengeti12

Reputation: 5586

Extracting a pattern that appers multiple times in a string using ruby regex

I want to extract patterns that appert multiple times in a string. For example,getting two an array lay of two digit integers from a string

wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56

I thought result="wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56".match(/([0-9]{2})/) should give a MatchData object whose captures method should give me an array of matched patters, but it seems there is something I am missing. It only give back the first find. Even using $1,$2,$3 etc doesn't work. I am using ruby

How should I do this?

Upvotes: 5

Views: 1538

Answers (2)

steenslag
steenslag

Reputation: 80065

scan does what you want:

str = "wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56"
p str.scan(/\d+/) #=> ["56", "67", "67", "45", "56"]

Upvotes: 6

ohaal
ohaal

Reputation: 5268

string.scan(/regex/)

should do it

Upvotes: 11

Related Questions