Home » Ruby Regular Expressions Tutorial (with Code Examples)

Ruby Regular Expressions Tutorial (with Code Examples)

Regular expressions (regex) are a powerful way to search, match, extract, and replace text in Ruby. Ruby has first-class regex support built right into the language, making text processing concise and expressive.

This tutorial explains Ruby regular expressions from the basics to practical real-world patterns, with plenty of clear examples.

1) What Are Regular Expressions in Ruby?

A regular expression is a pattern used to match text.

In Ruby, regex patterns are usually written between slashes:

/pattern/

Example:

puts "hello".match(/ell/)
# => #<MatchData "ell">

2) Matching Text (match, =~)

Using match

text = "Ruby is fun"

if text.match(/Ruby/)
  puts "Match found"
end

Using =~

puts "hello" =~ /ell/
# => 1 (starting index)

Returns nil if no match.

3) Character Classes

Basic character sets

/[abc]/     # a, b, or c
/[a-z]/     # lowercase letters
/[A-Z]/     # uppercase letters
/[0-9]/     # digits

Example:

puts "cat" =~ /[aeiou]/
# => 1

Negated character class

/[^0-9]/    # anything except digits

4) Quantifiers

| Quantifier | Meaning | | – | | | * | 0 or more | | + | 1 or more | | ? | 0 or 1 | | {n} | exactly n | | {n,} | n or more | | {n,m} | between n and m |

Example:

puts "aaa" =~ /a+/
# => 0

5) Anchors (^ and $)

Anchors match positions, not characters.

/^hello/    # start of string
/world$/    # end of string

Example:

puts "hello world" =~ /^hello/
# => 0

puts "hello world" =~ /world$/
# => 6

6) Capturing Groups and MatchData

Capturing groups

match = "2025-12-25".match(/(\d{4})-(\d{2})-(\d{2})/)

puts match[1] # year
puts match[2] # month
puts match[3] # day

Named captures

match = "2025-12-25".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/)

puts match[:year]
puts match[:month]
puts match[:day]

7) Alternation (|)

Match one pattern or another.

puts "cat" =~ /cat|dog/
puts "dog" =~ /cat|dog/

8) Substitution (sub and gsub)

Replace first match

text = "I like apples and apples"
puts text.sub(/apples/, "oranges")
# => I like oranges and apples

Replace all matches

puts text.gsub(/apples/, "oranges")
# => I like oranges and oranges

9) Splitting Strings with Regex

data = "one,two;three four"
parts = data.split(/[,; ]/)

p parts
# => ["one", "two", "three", "four"]

10) Common Real-World Regex Examples

Validate an email (basic)

email = "user@example.com"

if email =~ /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  puts "Valid email"
end

Remove extra whitespace

text = "  Ruby    is   fun  "
clean = text.gsub(/\s+/, " ").strip
puts clean
# => Ruby is fun

Extract numbers from a string

text = "Order #123 costs $45"
numbers = text.scan(/\d+/)

p numbers
# => ["123", "45"]

11) Regex Options (Flags)

Flag Meaning
i case-insensitive
m multiline
x extended (whitespace allowed)

Example:

puts "RUBY" =~ /ruby/i

12) Best Practices for Ruby Regex

  • Keep patterns readable
  • Use named captures for clarity
  • Avoid overly complex expressions
  • Test regex with real input
  • Comment complex patterns

 

FAQ

Q: How do I use regex in Ruby? A: Use patterns like /text/ with methods such as match, =~, sub, and gsub.

Q: What is MatchData in Ruby? A: MatchData holds the result of a regex match, including captures and match positions.

Q: Are Ruby regexes the same as PCRE? A: Ruby regex is similar to PCRE but has Ruby-specific features like named captures and global variables.

You may also like