ciaoben
ciaoben

Reputation: 3338

Why does match find only 1 group in this ruby regexp?

I have this string:

str = "\r\n <span>60 %</span>\r\n <br>\r\n40 %"

And I want to extract the 2 percentage, so I wrote this:

str.match(/(\d{1,2}\s%)/)

but it only returns the first one and can't understand why:

=> #<MatchData "60 %" 1:"60 %">

If I try this in rubular it works.

rubular version

Upvotes: 0

Views: 105

Answers (2)

Nermin
Nermin

Reputation: 6100

Use scan instead of the match, which only will find the first match.

str.scan(/(\d{1,2}\s%)/)

Will produce array of matches

["60 %", "40 %"]

Upvotes: 2

sawa
sawa

Reputation: 168101

It is by design. match finds the first match.

Upvotes: 0

Related Questions