move_slow_break_things
move_slow_break_things

Reputation: 847

Count capture groups ruby

I have a regex in my ruby script with a couple of capture groups. Here's a snippet of it: /^cost:\s(\d)+\sitems:\s 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?

Thanks

Upvotes: 0

Views: 455

Answers (2)

Jon Malachowski
Jon Malachowski

Reputation: 256

Consider using the scan method if you think you have non-deterministic split with a regex: http://ruby-doc.org/core-2.2.0/String.html#method-i-scan

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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:

#           ⇓
/^cost:\s(\d+)\sitems:\s.../

Upvotes: 3

Related Questions