Ruby 中匹配组的计数?

Count of matched groups in Ruby?

如果我有一个包含一组组的正则表达式(使用括号),其中一些是可选的(使用问号),我如何找到正则表达式匹配的组数?我知道 Python 有一个名为 groups() 的函数,它会告诉你,但你如何在 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

MatchData 有一个 #size#length 方法,但它们也会对空组进行计数,并且在所有三种情况下返回结果都会 3

看来唯一的解决办法就是下面这样

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

您可以像这样使用 Array#compact

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