Glossary Development

Regular expression

A regular expression (regex) is a pattern written in a compact syntax that describes a set of strings, used to search, validate and replace text.

Last reviewed:

AdSense Placeholder
Slot: header_reference_page

In more detail

A regular expression is a compact pattern language for matching text. Literal characters match themselves, while classes such as \d (a digit), quantifiers such as {3} or +, groups and anchors describe what may vary. Regex flavours differ slightly between languages, for example in lookbehind support and in how Unicode is handled. Very complex patterns become unreadable, and some can run catastrophically slowly on crafted input, so keep them simple on untrusted text.

Why it matters

Regex is the fastest way to validate, search and rewrite text in bulk, but it is easy to get subtly wrong: an unanchored pattern accepts junk around a valid match, and a greedy one can swallow more than intended. A pattern that backtracks exponentially lets one request freeze a server, which is a denial-of-service flaw known as ReDoS.

Example

The pattern \d{3}-\d{4} applied to Call 555-0142 or 555-0199, not 5550142 or 55-0142 finds two matches, 555-0142 and 555-0199, and skips the other two because they lack the hyphen or have too few digits. In contrast, (a+)+$ tested against a run of a characters followed by ! has to try every way of splitting the run, so the work roughly doubles with each extra a. Try patterns safely in the Regex Tester, and see Regular Expressions (Regex) Cheat Sheet.

Common confusion

Shell wildcards such as *.txt look similar but are a different, simpler language: in regex, * repeats the previous item, and .* is the "anything" part.

AdSense Placeholder
Slot: footer_leaderboard