samz_manu samz_manu - 1 year ago 80
Ruby Question

Count capture groups ruby

I have a regex in my ruby script with a couple of capture groups. Here's a snippet of it:


And I'm capturing the digit that comes right after cost. I have more capture groups later on but I don't know how many will get captured. Depends on the input text file. I know the way to access capture groups is with:

$1, $2 etc etc

But I don't know how many get captured. Is there a way to find out the number of groups that were captured and iterate through it maybe?


Answer Source

One might use MatchData#captures:

▶ mtch = /(\w)(\w)(\w)/.match 'hello'
#⇒ #<MatchData "hel" 1:"h" 2:"e" 3:"l">
▶ mtch.captures
#⇒ [
#  [0] "h",
#  [1] "e",
#  [2] "l"
# ]

Also note, that you actually capture a first digit in a sequence only. To capture all of them, move + inside parentheses:

#           ⇓
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download