Ruby regex basics
This course covers regular expressions in Ruby. It starts from the difference between checking one exact string with == and checking a shape with a pattern. It compares =~, match and match?, and explains MatchData and the $~ side effect. Later lessons cover numbered and named capture groups, collecting every occurrence with scan, the i flag, anchors, character classes and quantifiers. Search-and-replace with gsub and sub follows. The last lesson reads the regex that validates slugs in this app.
What you'll learn
- ✓Running a regex with =~, match and match?, and choosing between them
- ✓Extracting pieces of a match with numbered and named capture groups
- ✓Collecting every match with scan and ignoring case with the i flag
- ✓Anchoring a pattern with \A and \z, and how they differ from ^ and $
- ✓Character classes, shorthand like \d, \w and \s, and quantifiers
- ✓Replacing text with gsub and sub, using blocks and group references
Finding a pattern, not an exact string
That comparison answers a question about one specific string. A signup form doesn't know the visitor's email address in advance. It needs to check "does this look like an email": a shape, not an exact value. == can't express "some characters, then an @, then more characters, then a dot, then a few…
Read the full lesson free →Curriculum
7 lessonsFinding a pattern, not an exact string
Why == checks one exact string, how a Regexp literal works, and how =~ returns an index or nil.
MatchData or a plain Yes/No: match vs match?
Compares match, which returns MatchData, with match?, which returns a boolean and leaves $~ untouched.
Capture groups: pulling pieces out
Uses parentheses and named groups to pull pieces out of a match, and shows how groups change scan.
scan: collecting every match
Collects every match in a string with scan, explains its return shape with groups, and covers the i flag.
Anchors and character classes
Anchors with \A, \z, ^ and $, character classes with their shorthand, and quantifiers that control repetition.
Search-and-replace with gsub and sub
Replaces matches with gsub and sub, using fixed strings, blocks, and capture group references like \1.
Putting it together: the regex guarding this app's slugs
Reads the regex that validates course and lesson slugs in this app, piece by piece, and tests it.