Kleber S.
Kleber S.

Reputation: 8260

RegEx, How to get all matches and group? Ruby 1.9.3p125

Let's say I have the following string:

google-com, Awesome-net(Ooops), facebook-com / rocket-yet

I want to extract all the words ending with -com but have them grouped.

For now, I have tried:

^\w+[-]com

That works fine but only catches the first match. How to get all the others? Maybe something using parentheses but I can't figure out how to..

Having all the matched strings into an MatchData object (Ruby) I can work it like an Array.

I'm using ruby 1.9.3p125

1.9.3p125 :124 > original
 => "google-com, Awesome-net(Ooops), facebook-com / rocket-yet" 
1.9.3p125 :125 > results = original.match(/(\w+-com)/)
 => #<MatchData "google-com" 1:"google-com"> 

Upvotes: 0

Views: 435

Answers (3)

Kleber S.
Kleber S.

Reputation: 8260

Seems that match wasn't the right method to go.

Changed to scan with the regex suggested by Ben Roux and Epic_orange make it works.

Upvotes: 0

apple16
apple16

Reputation: 1147

Just use the findall option and this will work:

\w+-com

I tested it in http://rubular.com/

Upvotes: 2

Ben Roux
Ben Roux

Reputation: 7426

EDIT: found the issue, your regex has a caret at the start, symbolizing that only an instance of this at the very beginning of a string will match. Removing it should allow you to match all groups within the string:

(\w+[-]com)

Upvotes: 0

Related Questions