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


























