liveBook · Manning

Regular expression

As explained in The Well-Grounded Rubyist, Fourth Edition

Regexp is Ruby's built-in class for representing regular expressions and providing operations for constructing and manipulating them.

Suppose you need to find a title in a comma-separated record, check whether an entry has the right shape, or replace every occurrence of a word. A regular expression (regexp) describes a character pattern that a string may or may not match. In Ruby, it is a Regexp object, not a string. The same pattern can support a yes-or-no test, identify a substring, or drive a text-processing method. section 11.0 section 11.1 section 11.4.1

Start with a match

`/abc/.match?("The alphabet starts with abc.")` returns `true`. Use `match?` when that Boolean answer is all you need. `/abc/.match("def")` returns `nil`; a successful `match` instead returns a MatchData object. With `=~`, the matching string `"The alphabet starts with abc"` and `/abc/` produce `25`, the position where the match starts. The pattern `/abc/` does not require the whole string to equal `"abc"`. section 11.2.2 section 11.6

Write a regexp between slashes, as in `/abc/`, or with `%r{abc}`. What goes inside is a set of predictions about a string, not a string value. Literal characters predict themselves; `.` predicts any character except newline. Character classes offer alternatives for one character. Add quantifiers to specify repetition, anchors to constrain position, and modifiers to change matching behavior such as case sensitivity. section 11.2.2 section 11.3 section 11.8

Keep the parts you need

For `"Peel,Emma,Mrs.,talented amateur"`, `/([A-Za-z]+),[A-Za-z]+,(Mrs?\.)/` matches through the title. Parentheses capture the last name and title separately. The resulting MatchData records `"Peel"` as capture 1 and `"Mrs."` as capture 2; Ruby also makes them available as `$1` and `$2`. The `?` lets the title match either `Mr.` or `Mrs.`, while `\.` matches the period itself. section 11.4.1

MatchData is useful when a successful match needs more inspection: it provides captures, the text before and after the match, and capture positions. Check for `nil` before accessing a capture from `match`; a failed match does not return an empty MatchData object. Redefining `Regexp#match` globally to hide that distinction can disrupt other code that relies on its usual return values. section 11.4.4 section 13.2.1

Strings can supply pattern text through `#{...}` interpolation or `Regexp.new`, but their characters then acquire regexp meaning. Interpolating `"a.c"` produces a pattern whose dot can also match the `b` in `"abc"`. Use `Regexp.escape(str)` before interpolation when the string should be matched literally. For troubleshooting, `inspect` gives a string representation resembling the regexp as written. section 11.6.1 section 11.6.2

Beyond a single match, Ruby methods use regexps to scan for occurrences, split at matching separators, select matches with `grep`, and replace matches with `sub` or `gsub`. Regular expressions are compact and powerful, but can become hard to read; choose a pattern you can still understand when you return to it. section 11.1 section 11.8

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works from literals and match results through pattern components, captures, MatchData, interpolation, and escaping, without pursuing regexp string notation in depth.
Examples
Uses short matching expressions, a comma-separated name-and-title record, and an interpolated dot to expose different matching behaviors.
What it assumes
Assumes familiarity with Ruby strings and method calls while teaching regexp literals and basic pattern construction from the start.
What you can do after
Apply it via Ruby’s matching and string methods to test patterns, extract captures, and escape literal input.
How it connects
Connects regular expressions to String, Regexp, MatchData, character classes, captures, interpolation, and string substitution.

Also explained in

Compare how 27 books explain regular expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.