Regular Expressions (Regex) in Ruby
Regular Expressions (Regex) in Ruby
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"]
You can use parentheses () to create groups in a regex pattern and capture parts of
the string:
pattern = /(\w+)@(\w+)\.(\w+)/
result = pattern.match("[email protected]")
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
numbers = text.scan(/\d+/)
puts "Extracted numbers: #{numbers}" # Output: ["2", "3"]