How to Use Match in Ruby Regex: Syntax and Examples
In Ruby, you use
match to check if a string fits a regex pattern. It returns a MatchData object if it matches or nil if it doesn't. You call it like string.match(/pattern/).Syntax
The match method is called on a string and takes a regular expression as an argument. It returns a MatchData object if the regex matches part of the string, or nil if there is no match.
string.match(/pattern/): Checks ifpatternexists instring.MatchData: Contains details about the match, like matched text and groups.nil: Means no match was found.
ruby
result = "hello world".match(/world/) puts result.class puts result[0]
Output
MatchData
world
Example
This example shows how to use match to find a word in a string and access the matched text and capture groups.
ruby
text = "My phone number is 123-456-7890." match_data = text.match(/(\d{3})-(\d{3})-(\d{4})/) if match_data puts "Full match: #{match_data[0]}" puts "Area code: #{match_data[1]}" puts "Prefix: #{match_data[2]}" puts "Line number: #{match_data[3]}" else puts "No match found." end
Output
Full match: 123-456-7890
Area code: 123
Prefix: 456
Line number: 7890
Common Pitfalls
One common mistake is expecting match to return a boolean. It returns MatchData or nil, so you must check for nil before using the result. Another pitfall is forgetting to escape special characters in the regex.
ruby
text = "price is $5" # Wrong: assuming match returns true/false if text.match(/\$5/) puts "Found price" else puts "Price not found" end # Right: escape $ to match literal dollar sign if text.match(/\$5/) puts "Found price" else puts "Price not found" end
Output
Found price
Found price
Quick Reference
string.match(/regex/): ReturnsMatchDataornil.- Use
match_data[0]for full match. - Use
match_data[n]for capture groups. - Check for
nilbefore accessing match data. - Escape special characters like
$,.,?in regex.
Key Takeaways
Use
string.match(/pattern/) to find regex matches in Ruby strings.Always check if the result is
nil before using match data.Access the full match with
match_data[0] and groups with match_data[n].Escape special regex characters to match them literally.
Match returns
MatchData, not a boolean true/false.