Dasmowenator
Dasmowenator

Reputation: 5428

Count of matched groups in Ruby?

If I have a regex with a bunch of groups (using parentheses), some of which are optional (using question marks), how do I find the number of groups that were matched by the regex? I know Python has a function called groups() which will tell you, but how do you do it in Ruby?

m = /\d{2}(:\d{2}(:\d{2})?)?/.match('10') # I want to return 1
m = /\d{2}(:\d{2}(:\d{2})?)?/.match('10:30') # I want to return 2
m = /\d{2}(:\d{2}(:\d{2})?)?/.match('10:30:20') # I want to return 3

Upvotes: 0

Views: 146

Answers (2)

Nikita Misharin
Nikita Misharin

Reputation: 2020

MatchData has a #size and #length method, but they will count empty groups as well and returning result will 3 in all three cases.

So it seems that the only solution is something like the following

/\d{2}(:\d{2}(:\d{2})?)?/.match('10').to_a.compact.count

Upvotes: 2

user4932805
user4932805

Reputation:

You can use Array#compact like so:

/\d{2}(:\d{2}(:\d{2})?)?/.match('10').to_a.compact

Upvotes: 1

Related Questions