String#match?
regexp.match?(string) -> true or false Returns:
Boolean · Updated March 14, 2026 · String Methods regex matching performance boolean
The match? method performs a regex match and returns true or false without creating MatchData objects. This makes it faster than match when you only need to know if there’s a match.
Basic Usage
# Simple matching
/relo/.match?("Hello") # => true
/relo/.match?("World") # => false
Performance Advantage
# match? is faster because it doesn't create MatchData
email = "user@example.com"
pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
# With match? - just boolean check
pattern.match?(email) # => true
# With match - creates MatchData object (slower)
pattern.match(email) # => #<MatchData "user@example.com">
Practical Examples
Validation
def valid_email?(email)
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.match?(email)
end
valid_email?("test@example.com") # => true
valid_email?("invalid") # => false
Conditional Processing
text = "Error: Something went wrong"
if /Error/.match?(text)
puts "Errors found in: #{text}"
end
Multiple Patterns
patterns = [/ruby/, /python/, /go/]
text = "I love programming in ruby"
patterns.any? { |p| p.match?(text) } # => true
With Position (Ruby 2.7+)
# Can specify start position
"hello world".match?(/world/, 6) # => true
"hello world".match?(/world/, 0) # => false
Return Value
# Returns true or false
result = /cat/.match?("concatenation")
puts result # => true (substring exists)
# No MatchData created
result = /(\d+)/.match?("abc123")
puts result # => true, but $1 is nil (no capture)
Comparison with Other Methods
pattern = /\d+/
# match? - just boolean, no MatchData
pattern.match?("abc123") # => true
# match - returns MatchData or nil
pattern.match("abc123") # => #<MatchData "123">
# =~ - returns position or nil
pattern =~ "abc123" # => 3
Use Cases
- Validation checks
- Conditional branching based on presence
- Performance-critical code
- When you don’t need match details