Ruby idiom for all matches in a string

D

David Corbin

What's the ruby idiom for all the matches in a string.

x="ABA ABBBA CBBA"
/A(B+)/.match(x)

Ultimately, I want to get [ "B", "BBB" ]

Thanks
 
R

Robert Klemme

David Corbin said:
What's the ruby idiom for all the matches in a string.

x="ABA ABBBA CBBA"
/A(B+)/.match(x)

Ultimately, I want to get [ "B", "BBB" ]


With only one grouping expression you can do:

x.scan(/A(B+)/).flatten

In case the first part would be more complex you can still use non
grouping brackets:

x.scan(/(?:A)(B+)/).flatten

Regards

robert
 
R

Robert Klemme

Robert Klemme said:
David Corbin said:
What's the ruby idiom for all the matches in a string.

x="ABA ABBBA CBBA"
/A(B+)/.match(x)

Ultimately, I want to get [ "B", "BBB" ]


With only one grouping expression you can do:

x.scan(/A(B+)/).flatten

In case the first part would be more complex you can still use non
grouping brackets:

x.scan(/(?:A)(B+)/).flatten

Or you do an additional select step:

x.scan(/(A)(B+)/).map {|m| m[1]}

Cheers

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top