Regular expressions (regex) in Ruby are patterns used to match, search, and
manipulate strings. Ruby provides extensive support for regular expressions, and
they are represented as /pattern/ in Ruby.
In Ruby, regular expressions are created between slashes (/) or by using %r{},
especially if the pattern contains slashes:
pattern = /ruby/
pattern_alt = %r{ruby}
=~ (Match Operator)
The =~ operator checks if a pattern matches a string. It returns the position of
the first match or nil if there’s no match.
puts "I love Ruby!" =~ /Ruby/ # Outputs: 7
puts "Hello" =~ /Ruby/ # Outputs: nil
.match Method
The .match method returns a MatchData object if the pattern matches, which includes
details about the match.
result = /Ruby/.match("I love Ruby!")
puts result[0] # Outputs: Ruby
.scan Method
The .scan method finds all occurrences of the pattern in the string and returns
them as an array.
puts "I love Ruby and Ruby on Rails!".scan(/Ruby/)
# Outputs: ["Ruby", "Ruby"]
.sub and .gsub Methods
.sub replaces the first occurrence of the pattern with a given replacement string.
.gsub replaces all occurrences of the pattern.
puts "I love Ruby".sub(/Ruby/, "Python") # Outputs: I love Python
puts "Ruby is great. Ruby is fun.".gsub(/Ruby/, "Python")
# Outputs: Python is great. Python is fun.
^ and $ : ^ matches the start and $ matches the end of a line
"Ruby".match(/^R/) # Matches only if the string starts with 'R'
* : Matches 0 or more occurrences of the preceding element
"Ruby!".match(/u*/)
+ : Matches 1 or more occurrences of the preceding element
"Ruby".match(/u+/) # Matches
? : Matches 0 or 1 occurrence of the preceding element
"Ruby".match(/u?/) # Matches
\d : Matches any digit (0-9).
"123".match(/\d+/) # Matches "123"
\w : Matches any word character (alphanumeric and underscore).
"ruby_123".match(/\w+/) # Matches "ruby_123"
\s : Matches any whitespace character (space, tab, newline)
" ".match(/\s/) # Matches
You can use parentheses () to create groups in a regex pattern and capture parts of
the string:
pattern = /(\w+)@(\w+)\.(\w+)/
result = pattern.match("user@example.com")
Examples:
Example 1: Basic Pattern Matching
# Check if a string contains a pattern
text = "hello world"
if text =~ /world/
puts "Found 'world' in the text"
else
puts "'world' not found in the text"
end
Example 2: Extracting Numbers from a String
# Extract all numbers from a string
text = "I have 2 apples and 3 bananas."
numbers = text.scan(/\d+/)
puts "Extracted numbers: #{numbers}" # Output: ["2", "3"]
Example 3: Finding All Words in a String
# Find all words in a string
text = "Ruby is a beautiful language!"
words = text.scan(/\b\w+\b/)
puts "Words: #{words}" # Output: ["Ruby", "is", "a", "beautiful", "language"]
Example 4: Matching Phone Numbers
# Match a simple phone number format (e.g., 123-456-7890)
phone = "123-456-7890"
if phone =~ /^\d{3}-\d{3}-\d{4}$/
puts "Valid phone number format"
else
puts "Invalid phone number format"
end
Example 5:Removing Vowels from a String
# Remove all vowels from a string
text = "Hello, Ruby!"
no_vowels = text.gsub(/[aeiouAEIOU]/, "")
puts no_vowels # Output: "Hll, Rby!"