Ruby Examples > Regular Expressions

#---Regular Expressions---

Regular expressions (regexp) in Ruby provide powerful pattern matching and text manipulation. In Ruby, regexp is implemented using the Regexp class.

Create a regular expression

Ruby provides several ways to create regular expressions: Using /.../ The most common way to create a regex is by enclosing the pattern in forward slashes.

regex = /hello/

Using %r{...} This is useful when your regex contains forward slashes, as it avoids the need to escape them.

regex = %r{https?://}

Using Regexp.new You can also create a regex using the Regexp.new method, which is useful when the pattern is dynamic.

pattern = "hello"
regex = Regexp.new(pattern)

Check if a string matches a pattern

The most common use of regexp is to check if a string matches a specific pattern.
You can use the match? method or the =~ operator.

The match? method (from ruby 3.x) is preferred because it returns a boolean without creating a MatchData object, making it more efficient.

Using Regexp#match? method:

## Check if string ends with one or more digits
if /\d+$/.match?("The answer is 42")
  p "Match found!" # => "Match found!"
else
  p "No match."
end

Using Regexp#=~ method:

if /hello/ =~ "The answer is 42"
  p "Match found!"
else
  p "No match." # => "No match."
end

Capture matching data

It’s also useful to capture just the data that’s matching your pattern. For example, in a text blurb, you might want to extract just the dates.

To help with that when a regex matches a string, Ruby creates a MatchData that contains information about the match. You can access this object using the match method.

str = "Today's date is 10-25-2025."
re = /(\d{2})-(\d{2})-(\d{4})/
md = re.match(str)
if md
  p "Full match: #{md[0]}" # => "Full match: 10-25-2025"
  p "Day: #{md[1]}"        # => "Day: 10"
  p "Month: #{md[2]}"      # => "Month: 25"
  p "Year: #{md[3]}"       # => "Year: 2025"
end

Common Use Cases

Validate an email:

re = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
p re.match?("user@example.com") # => true
p re.match?("invalid.email@") # => false

String substitution:

p "hello world".gsub(/world/, 'ruby') # => "hello ruby"
p "hello WORLD".gsub(/\w+/) { |word| word.capitalize }
## => "Hello World"
p "John Doe".gsub(/(?<first>\w+)\s(?<last>\w+)/,
                '\k<last>, \k<first>') # => "Doe, John"

Parse a URL:

re = %r{
  \A
  (?<protocol>https?://)
  (?<domain>[^/]+)
  (?<path>/[^?#]*)?
  (?<query>\?[^#]*)?
  (?<fragment>\#.*)?
  \z
}x
md = "https://example.com/path?q=1#section".match(re)
p md[:protocol]  # => "https://"
p md[:domain]    # => "example.com"
p md[:path]      # => "/path"
p md[:query]     # => "?q=1"
p md[:fragment]  # => "#section"

Notes & Reference