0
0
Rubyprogramming~5 mins

Capture groups in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a capture group in Ruby regular expressions?
A capture group is a part of a regular expression enclosed in parentheses (). It saves the matched text so you can use it later.
Click to reveal answer
beginner
How do you access the text matched by the first capture group in Ruby?
You can access it using $1 after the match or by using MatchData[1] if you use =~ or match methods.
Click to reveal answer
beginner
What does this Ruby code output?<br>
text = 'Name: John'
if text =~ /Name: (\w+)/
  puts $1
end
It outputs John because the capture group (\w+) matches the word after 'Name: ' and $1 holds that match.
Click to reveal answer
intermediate
Can capture groups be nested in Ruby regular expressions?
Yes, capture groups can be nested. Each pair of parentheses creates a new group, and you can access them by their order of opening parentheses.
Click to reveal answer
intermediate
What is the difference between a capture group and a non-capturing group in Ruby regex?
A capture group saves the matched text for later use. A non-capturing group, written as (?:...), groups parts of the pattern without saving the match.
Click to reveal answer
In Ruby, what does the capture group (\d+) match?
AOne or more digits
BOne or more letters
CAny character except digits
DExactly one digit
How do you write a non-capturing group in Ruby regex?
A[pattern]
B(?:pattern)
C(pattern)
D{pattern}
After matching with /Hello (\w+)/, how do you get the captured word in Ruby?
A$1
B$0
Cmatch[0]
Dmatch[2]
What will /(a(b))/.match('ab')[2] return in Ruby?
Anil
Bab
Ca
Db
Which of these is true about capture groups in Ruby regex?
AThey change the original string
BThey only match digits
CThey save matched text for later use
DThey cannot be nested
Explain what a capture group is and how you use it in Ruby regular expressions.
Think about how parentheses help you save parts of the matched text.
You got /3 concepts.
    Describe the difference between a capturing group and a non-capturing group in Ruby regex.
    One saves the match, the other just groups without saving.
    You got /3 concepts.