What are regular expressions in Ruby?
Regular expressions in Ruby are user-determined strings that we can use for pattern-matching in a text. We use these patterns to determine whether the ‘target’ string has the characteristics defined in the pattern.
Modifiers
Modifier | Description |
i | This modifier makes the pattern matching case-sensitive. |
o | This modifier makes sure that the pattern is only matched once. |
x | This modifier allows the use of whitespace in the pattern. |
m | This modifier matches multiple lines. |
u,e,s,n | These modifiers interpret the expression as Unicode (UTF-8), EUC, SJIS, or ASCII. By default, the regular expression is assumed to use the source encoding. |
Definition
We define the regular expression by enclosing it within two forward slashes.
str = /my expression/
Matching
There are two common ways of using the regular expressions for matching:
- Using
=~operator
"Do you contain my expression" =~ /expression/
This returns the index of the position at which the expression is found in the string. If the expression is not found, it returns an empty string.
- Using
matchfunction
if "Do you contain my expression?".match(/expression/)
puts "Match found!"
end
This function only checks if the string contains the expression and then returns true or false.
Code
Let’s look at an example of how to use regular expressions in Ruby:
# Example code for regular expressions# displays index of expressionputs "Do you contain my expression?" =~ /expression/# displays nothing when the expression is not foundputs "Do you contain my expression?" =~ /not/# using the match functionif "Do you contain my expression?".match(/expression/)puts "Match found!"end# using a modifier 'i' for case insensitivityif "Do you contain my expression".match(/EXPRESSION/i)puts "Case insensitive match found!"end
Free Resources