Regex in Ruby
Write regular expressions in Ruby to match, search, and manipulate strings using the Regexp class.
Introduction to Regular Expressions
A regular expression (regex) is a pattern used to match, search, validate, or replace text. Ruby has first-class regex support built in — no `require` needed. Regex literals use `/pattern/flags` syntax, similar to JavaScript.
1. What Is a Regular Expression?
Pattern-based string matching using the `=~` operator.
2. The =~ Operator
`=~` returns the index of the first match, or nil if no match.
Creating Regex Patterns
Ruby supports both the `/pattern/` literal and `Regexp.new("pattern")` constructor. Use literals for static patterns and the constructor for dynamic patterns.
1. Regex Literal
Use `/pattern/flags` — compiled at parse time.
2. Regexp.new (Dynamic Patterns)
Build a pattern from a string at runtime.
Regex Flags
Ruby supports flags appended after the closing `/`. Common flags: `i` (case-insensitive), `m` (dot matches newline), `x` (extended — allows whitespace and comments in pattern).
1. i — Case-Insensitive
Match regardless of letter case.
2. m — Multiline (dot matches newline)
In Ruby, `m` makes `.` match newlines too.
3. x — Extended Mode
Add whitespace and comments inside the pattern for readability.
Regex Methods
Ruby strings have built-in regex methods. `match` finds the first match, `scan` finds all, `sub` replaces the first, `gsub` replaces all, and `split` divides by a pattern.
1. match / match?
`match` returns a MatchData object; `match?` returns boolean.
2. scan — Find All Matches
`scan` returns an array of all non-overlapping matches.
3. sub and gsub — Replace
`sub` replaces the first match; `gsub` replaces all.
4. split with Regex
Split a string on a regex pattern.
Character Classes & Anchors
Character classes like `\d`, `\w`, `\s` match common groups. Anchors like `\A`, `\z`, `^`, `$` match positions in the string.
1. Common Character Classes
\d, \w, \s and negations.
2. Anchors
`\A` / `\z` for string start/end; `^` / `$` for line start/end.
3. Quantifiers
Control how many times a pattern repeats.
Named Capture Groups
Ruby supports named capture groups using `(?<name>pattern)`. They make complex patterns much more readable than numbered groups.
1. Named Capture Groups
Access matched parts by name instead of index.
2. gsub with a Block
Transform each match dynamically using a block.
Practical Validation
Regex is commonly used for input validation. Ruby's `\A` and `\z` anchors ensure the entire string is validated, not just a substring.
1. Email Validation
Simple regex to validate email format.
2. Extracting All Numbers from Text
Use scan to pull all numbers from a string.