18bytes
18bytes

Reputation: 6029

How can I get a list of regex matches for a group?

I have a group which can occur any number of times in the input string. I need to get a list of all the matching items.

For example, for input:

example repeattext 1 anything here repeattext 2 anything repeattext 3

My regex is:

 (repeattext \d)

I want to get the list of matches for the group. Is it possible to use regex here or do I need to parse it myself?

Upvotes: 0

Views: 79

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336148

Use

result = subject.scan(/repeattext \d+/)
=> ["repeattext 1", "repeattext 2", "repeattext 3"]

See the docs for the .scan() method.

Upvotes: 1

ohaal
ohaal

Reputation: 5268

Yes, you can use regex here. Your existing regex will do fine.

See http://rubular.com/r/fS8c9C61rG for it in use on your example.

If numbers will ever become 10 or higher, consider this regex:

(repeattext \d+)
              ^
              |
              `- matches 1 or more repeating of previous

Upvotes: 1

Related Questions