How to Use Regex in Ruby: Syntax and Examples
In Ruby, you use regular expressions with the
// syntax to create patterns and methods like =~ or match to test strings. Regex helps find, match, or replace text easily within strings.Syntax
Ruby uses // to define a regular expression pattern. You can use methods like =~ to check if a string matches the pattern, or match to get detailed match data.
- //: Defines the regex pattern.
- =~: Returns the index of the match or
nilif no match. - match: Returns a
MatchDataobject with details ornil.
ruby
pattern = /ruby/
text = "I love ruby programming"
index = text =~ pattern
match_data = text.match(pattern)Example
This example shows how to check if a string contains the word "ruby" and how to extract it using regex.
ruby
pattern = /ruby/ text = "I love ruby programming" if text =~ pattern puts "Found 'ruby' at index: #{text =~ pattern}" puts "Matched text: #{text.match(pattern)[0]}" else puts "No match found" end
Output
Found 'ruby' at index: 7
Matched text: ruby
Common Pitfalls
Common mistakes include forgetting to escape special characters, confusing =~ with ==, and not handling nil when no match is found.
Always check if the match result is nil before using it to avoid errors.
ruby
text = "Price is $5" # Wrong: forgetting to escape $ (special char) pattern_wrong = /\$5/ puts text =~ pattern_wrong # returns 9 # Right: escape $ with backslash pattern_right = /\$5/ puts text =~ pattern_right # returns index 9
Output
9
9
Quick Reference
| Regex Feature | Description | Example |
|---|---|---|
| /pattern/ | Defines a regex pattern | /ruby/ |
| =~ | Returns index of match or nil | "text" =~ /ex/ |
| match | Returns MatchData or nil | "text".match(/ex/) |
| \d | Matches any digit | /\d+/ |
| \w | Matches any word character | /\w+/ |
| ^ | Start of string | /^Hello/ |
| $ | End of string | /world$/ |
| * | Zero or more repetitions | /a*/ |
| + | One or more repetitions | /a+/ |
| ? | Zero or one repetition | /a?/ |
Key Takeaways
Use
// to create regex patterns in Ruby.Use
=~ to check if a string matches a pattern and get the match index.Use
match to get detailed match information or nil if no match.Always escape special characters like
$ in regex patterns.Check for nil results to avoid errors when no match is found.