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.
This modifier makes the pattern matching case-sensitive.
This modifier makes sure that the pattern is only matched once.
This modifier allows the use of whitespace in the pattern.
This modifier matches multiple lines.
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.
We define the regular expression by enclosing it within two forward slashes.
str = /my expression/
There are two common ways of using the regular expressions for matching:
"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.
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
Let’s look at an example of how to use regular expressions in Ruby:
# Example code for regular expressions # displays index of expression puts "Do you contain my expression?" =~ /expression/ # displays nothing when the expression is not found puts "Do you contain my expression?" =~ /not/ # using the match function if "Do you contain my expression?".match(/expression/) puts "Match found!" end # using a modifier 'i' for case insensitivity if "Do you contain my expression".match(/EXPRESSION/i) puts "Case insensitive match found!" end
View all Courses