11 Regular expressions and regexp-based string operations
This chapter introduces Ruby’s regular expression system as a practical way to describe patterns in text and then use those patterns to test, extract, filter, and transform strings. It emphasizes that regexes are objects of the Regexp class, so they participate in normal Ruby message passing, and it compares simple match checks such as match?, match, and =~ to show how Ruby reports success, failure, and match position.
The discussion then builds up the language of regular expressions itself: literal characters, escaped special characters, the wildcard dot, character classes and ranges, predefined shorthand classes like \d, \w, and \s, as well as alternation with |. It also explains how quantifiers control repetition, including zero-or-one, zero-or-more, one-or-more, exact counts, ranges, greedy versus non-greedy behavior, and the need to place parentheses carefully when repetition and capture interact.
The later sections focus on match results and common regex-based string operations. Ruby’s MatchData object exposes the matched substring, captures, named captures, pre- and post-match text, and position information, while global and named capture variables provide shortcuts for accessing those pieces. The chapter closes by showing how regular expressions power methods such as scan, split, sub, gsub, grep, and case matching, and it also covers anchors, lookahead and lookbehind assertions, modifiers like i, m, and x, and conversion techniques between strings and regexes for interpolation, escaping, and debugging.
Summary
- This chapter has examined the underlying principles behind regular expression pattern matching.
- The match? method provides a yes/no (true/false) answer to “Is there a match?” between a string and a regular expression.
- Character classes, which include explicit ones inside square brackets, predefined ones (\d, \w, and so on), and POSIX bracket notation, match single characters against multiple alternatives.
- The match method generates MatchData objects, which encapsulate information about the match: where in the string the match happened, which characters come before and after the match, and more.
- Parenthetical captures, which can be accessed via numbered global variables or through a MatchData object, allow for zeroing in on particular parts of a match.
- Quantifiers let you specify number of occurrences of a match (one-or-more, for example).
- Modifiers govern certain characteristics of a match operation (case-insensitivity, for example).
- Anchors specify where in the string a match is being asserted (beginning-of-line, for example).
- Strings and regexp objects obey certain rules when it comes to interpolation (of a string into a regex) and conversion (from one to the other).
- Numerous Ruby methods use regexps, including: scan, split, grep, sub, and gsub.
The Well-Grounded Rubyist, Fourth Edition ebook for free