Learn regular expressions · Lesson 1
What a regular expression is
A regular expression, regex for short, is a pattern that describes a piece of text. You give an engine the pattern and a text, and it tells you where in the text the pattern matches: to find something, to check that a whole string has the right shape, to pull parts out of it, or to replace them.
The engine is the code that runs the pattern: PCRE2 in PHP, re in Python, the one built into each browser for JavaScript. Each has its own dialect of regular expressions, its flavor. The basics in these lessons work the same nearly everywhere; where flavors differ, a box says how.
Letters match themselves
Most characters in a pattern stand for themselves. The pattern cat matches the three letters c, a and t, one after the other, wherever they are, inside other words too:
/cat/g3 matchesThe cat sat on the concatenated catalogue.Try it in Dotstar →
The engine goes through the text from the start, and at each position tries the pattern. The first place it fits is the first match; with the g flag (global) it carries on after it and finds every match, as above. Without g, most tools stop at the first:
/cat/1 matchThe cat sat on the concatenated catalogue.Try it in Dotstar →
Case matters
cat doesn’t match Cat: capitals are different characters. The i flag (ignore case) makes them the same:
/cat/gi3 matchesCat, CAT and cat.Try it in Dotstar →
What comes next
Letters alone only find fixed text, which any editor’s search does. Regular expressions get their power from a handful of characters that mean something else: a dot for any character, * for “any number of”, brackets for “one of these”. The next lesson is about those characters, and how to match them when you mean the character itself.