Regular Expressions
Ruby is a dynamic, beginner-friendly programming language with excellent built-in regular expressions — compact patterns for matching, extracting, and replacing text.
Learn Regular Expressions in our free Ruby course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Ruby course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
By the end of this lesson you'll write patterns, test matches, capture pieces of text, and transform strings with gsub and scan.
What You'll Learn in This Lesson
1️⃣ Matching: Patterns, Classes, and Anchors
A pattern lives between slashes: /world/ . Test it with match? (true/false) or =~ (index or nil). The building blocks are character classes like \d (digit) and \w (word char), anchors ^ / $ , and quantifiers like + .
2️⃣ Extracting and Transforming
Wrap parts of a pattern in () to capture them, then read data[1] , data[2] , and so on. scan collects every match into an array; gsub replaces them all; and split can break a string on a pattern.
Your turn. Use a pattern to validate emails and extract a domain. The pattern is supplied — read the TODO note to understand each piece, then run it.
Mini-Challenge: Extract Phone Numbers
Use scan with a digit pattern to pull every phone number out of a sentence. Run with ruby phones.rb .
Common Errors (and the fix)
- Forgetting to escape special chars — A literal dot is \. ; an unescaped . matches any character.
- nil from match — match returns nil on no match. Guard before reading data[1] .
- Greedy quantifiers — .* grabs as much as possible. Use .*? for lazy matching.
- ^/$ vs \A/\z — ^ / $ match line boundaries; for whole-string anchoring use \A / \z .
- Over-complex patterns — Email/URL validation is famously hard. Keep patterns simple and validate further in code.
Pro Tips
- 💡 The i flag: /cat/i matches case-insensitively.
- 💡 Named groups: /(?<year>\d{4})/ reads as data[:year] .
- 💡 Test interactively: a tool like rubular.com shows matches live as you type.
📋 Quick Reference — Regular Expressions
Concept
Ruby Syntax
Test match
s.match?(/pat/)
Digit / word / space
\d \w \s
One+ / optional
+ ? * {2,4}
Capture
s.match(/(\d+)/)[1]
All matches
s.scan(/\w+/)
Replace all
s.gsub(/x/, "y")
Frequently Asked Questions
🎉 Lesson Complete!
- ✅ Patterns go between slashes: /pat/
- ✅ Test with match? or =~
- ✅ \d \w \s , anchors, and quantifiers build patterns
- ✅ Capture groups () extract pieces of text
- ✅ scan collects matches; gsub replaces them
- ✅ Next lesson: File I/O — read and write files on disk
Practice quiz
What does ("hello world" =~ /world/) return?
- true
- 0
- 6
- nil
Answer: 6. =~ returns the index where the match starts; "world" begins at index 6.
What does ("hello" =~ /xyz/) return?
- nil
- false
- 0
- -1
Answer: nil. =~ returns nil when there is no match.
What does the character class \d match?
- Any word character
- Whitespace
- Any letter
- Any digit
Answer: Any digit. \d matches any single digit 0-9.
What does \w match?
- Whitespace only
- A word character (letters, digits, underscore)
- Only letters
- Any character
Answer: A word character (letters, digits, underscore). \w matches a word character: letters, digits, or underscore.
Which method returns a simple true/false for a match?
- match?
- scan
- match
- =~
Answer: match?. match? returns a boolean and is the fastest yes/no check.
After m = "2026-06-17".match(/(\d{4})-(\d{2})-(\d{2})/), what is m[1]?
- "2026-06-17"
- "06"
- "2026"
- "17"
Answer: "2026". m[0] is the whole match; m[1] is the first capture group, "2026".
What does "cat bat rat".scan(/\w+at/) return?
- "cat"
scan finds all matches and returns them in an array.
What does "2026-06-17".gsub(/-/, "/") return?
- "2026-06-17"
- "2026/06-17"
- nil
- "2026/06/17"
Answer: "2026/06/17". gsub replaces every match, turning all dashes into slashes.
What does "a1b2c3".split(/\d/) return?
split breaks the string on each digit, leaving the letters.
Which flag makes a pattern match case-insensitively?
- /pat/g
- /pat/m
- /pat/i
- /pat/x
Answer: /pat/i. The i flag, as in /cat/i, matches case-insensitively.
Continue this course
- Previous: Exception Handling
- Next: File I/O