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
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.../
如果您认为使用正则表达式进行了不确定的拆分,请考虑使用扫描方法: http : //ruby-doc.org/core-2.2.0/String.html#method-i-scan
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.