Skip to content

Regex

One line: Perl's regex engine is the one the others copied, and its sharp edges are about context more than syntax: what \w matches depends on a feature, what /g returns depends on list or scalar context, s/// and tr/// return counts rather than strings, and split has rules of its own for empty fields.

PCRE — the library behind grep -P, PHP and a hundred other tools — stands for Perl Compatible Regular Expressions. So the syntax here will look familiar from everywhere. What does not travel is the part that is Perl rather than regex: context, pos(), the return value of an operator, and the storage-dependent rules this chapter opens with.

Lesson Level What it settles
The Unicode bug 201 Why é =~ /\w/ depends on the string's storage without use v5.12, what \d matches with it, and what /a and /aa take back
/g in list and scalar context 201 Every match at once or one per call; pos(); the if (/.../g) that starts in the wrong place; and a match in an argument list
s/// and tr/// return counts 101 What my $new = $old =~ s/…/…/ stores, /r, /e, and a tr that is not a regex and does not interpolate
split has sharp edges 101 Empty fields at both ends, a string that is still a pattern, the special ' ', captured separators, and the limit you did not ask for

Where this connects