How to Use Capture Groups in Ruby: Simple Guide
In Ruby, you use
capture groups by placing parts of your regular expression inside parentheses (). These groups let you extract specific parts of a matched string using methods like match and accessing the groups with MatchData objects.Syntax
Capture groups in Ruby are created by wrapping parts of a regular expression in parentheses (). Each group captures the text matched inside it.
(pattern): Defines a capture group.match(string): Applies the regex to a string and returns aMatchDataobject.match_data[n]: Accesses the nth capture group (1-based index).
ruby
regex = /(\w+)@(\w+)\.com/ match_data = regex.match("user@example.com") puts match_data[1] # captures 'user' puts match_data[2] # captures 'example'
Output
user
example
Example
This example shows how to extract the username and domain from an email address using capture groups.
ruby
email = "alice@openai.com" regex = /(\w+)@(\w+)\.com/ match = regex.match(email) if match puts "Username: #{match[1]}" puts "Domain: #{match[2]}" else puts "No match found" end
Output
Username: alice
Domain: openai
Common Pitfalls
One common mistake is forgetting that match_data[0] returns the whole matched string, not a capture group. Also, capture groups are numbered by their order of opening parentheses, so nested groups count too.
Another pitfall is using scan without understanding it returns arrays of matches, not MatchData.
ruby
text = "Name: John Doe" regex = /Name: (\w+) (\w+)/ match = regex.match(text) puts match[0] # whole match puts match[1] # first name puts match[2] # last name # Wrong: expecting scan to return MatchData matches = text.scan(/(\w+) (\w+)/) puts matches.inspect # returns array of arrays
Output
Name: John Doe
John
Doe
[["John", "Doe"]]
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Capture Group | Parentheses in regex to capture text | /(\w+)/ |
| Access Group | Use MatchData[n] to get group n | match[1] |
| Whole Match | Group 0 is the full matched string | match[0] |
| Nested Groups | Counted by order of opening parentheses | /(a(b)c)/ |
| scan method | Returns array of matches, not MatchData | text.scan(/(\w+)/) |
Key Takeaways
Use parentheses () in regex to create capture groups in Ruby.
Access captured parts with MatchData objects returned by match method.
Group 0 is the full match; groups start numbering from 1.
Nested groups count in numbering order of opening parentheses.
scan returns arrays of matches, not MatchData objects.