A regular expression, usually shortened to regex, is a compact pattern that describes a set of strings, which a regex engine uses to search, validate, extract or replace text. In programming, regular expressions are one of the most widely shared fundamentals: nearly every language, editor, database and command-line tool supports them, from grep and sed to JavaScript, Python, Java and SQL dialects.
A pattern such as ^\d{3}-\d{4}$ reads as a precise rule: start of input, three digits, a hyphen, four digits, end of input. The idea comes from formal language theory, where regular expressions describe exactly the languages that a finite automaton can recognize, but practical regex dialects add features that go well beyond that theoretical model.
How a regex engine matches text
A regex engine compiles the pattern into an automaton or an internal program and then runs it against the input string. The compiled form is reused, which is why most libraries let developers precompile a pattern once and apply it many times inside a loop.
Two engine families dominate. Backtracking engines (used by Perl, PCRE, Python, Java, JavaScript and .NET) try alternatives one at a time and retreat when a path fails; they support rich features but can take exponential time on hostile patterns. Automaton-based engines such as RE2, Rust regex and Go regexp simulate a finite automaton and guarantee linear time in the input length, at the cost of dropping backreferences and some lookaround constructs.
The table below compares the two engine designs on the properties that most often decide which one a project should use.
| Property | Backtracking engine | Automaton-based engine |
|---|---|---|
| Typical examples | PCRE, Python re, Java, JavaScript | RE2, Go regexp, Rust regex |
| Worst-case running time | Exponential on some patterns | Linear in input length |
| Backreferences | Supported | Not supported |
| Lookahead and lookbehind | Supported | Absent or limited |
| Best fit | Feature-rich text processing | Untrusted input and services |
Matching usually returns the leftmost match, and within that position backtracking engines return the first alternative that succeeds, while POSIX engines are required to return the leftmost-longest match. This difference explains why the same pattern can capture different text in different tools.
Core regex syntax and its building blocks
Every regular expression combines a small set of building blocks: literal characters, character classes, quantifiers, anchors, groups and alternation. Mastering these six elements covers most real-world patterns, and the rest of the syntax is refinement.
The following table lists the most common constructs with their meaning and a short illustration in the widely used Perl-compatible notation.
| Construct | Meaning | Example match |
|---|---|---|
Character class [a-z] | One character from the set | [aeiou] matches “e” |
Shorthand class \d \w \s | Digit, word character, whitespace | \d+ matches “2048” |
Quantifier * + ? {m,n} | Repeat the preceding item | a{2,3} matches “aaa” |
Anchor ^ $ \b | Position, not a character | \bcat\b skips “concat” |
Group ( ) | Capture or combine a subpattern | (ab)+ matches “abab” |
Alternation | | Either of two options | jpe?g|png matches “png” |
Quantifiers are greedy by default: they consume as much text as possible and give characters back only if the rest of the pattern fails. Adding ? makes them lazy, so ".*?" stops at the first closing quote instead of the last one on the line. Non-capturing groups written as (?:...) group items without storing a capture, which keeps numbering simple and saves memory.
Most engines also accept flags that change behavior globally: case-insensitive matching, multiline mode in which ^ and $ match at every line break, dot-all mode in which . also matches newlines, and verbose mode that permits whitespace and comments inside the pattern for readability.
Regex dialects across languages and tools
There is no single regex standard in practice. POSIX defines basic and extended regular expressions, while most modern languages follow Perl-compatible syntax with local differences in Unicode handling, named groups and lookbehind support.
| Dialect | Where it appears | Notable trait |
|---|---|---|
| POSIX BRE | Classic grep and sed | Braces and groups need backslashes |
| POSIX ERE | egrep, awk, grep -E | Leftmost-longest matching rule |
| PCRE | PHP, many editors, grep -P | Rich lookaround and recursion |
| ECMAScript | JavaScript and TypeScript | Unicode mode with the u flag |
| RE2 syntax | Go, Google services | No backreferences, linear time |
Because of these differences, a pattern copied from one environment can fail silently in another. A careful developer always tests a pattern in the target engine, not merely in a generic online tester, and checks how that engine defines word characters and case folding for non-ASCII text.
When to use a regular expression and when not to
A regular expression is the right tool when the text has a flat, describable structure: log lines, identifiers, dates, simple tokens or search-and-replace refactoring. It is the wrong tool when the input has nested or recursive structure, because a true regular language cannot count matching brackets to arbitrary depth.
The decision table below summarizes typical situations and the approach that experienced developers usually choose.
| Situation | Recommended approach | Reason |
|---|---|---|
| Extract fields from log lines | Regex with named groups | Flat, repetitive structure |
| Parse HTML, XML or JSON | Dedicated parser | Nested structure breaks patterns |
| Check a fixed prefix | Plain string method | Faster and clearer than regex |
| Validate an email address | Simple regex plus confirmation | Full grammar is impractical |
| Tokenize a programming language | Lexer built on regex rules | Regex per token, parser above |
Regex also interacts with neighboring fundamentals. It operates on the string data type, usually returns a Boolean result for validation or a match object for extraction, and is often wrapped in a function with clear parameters so that the pattern is documented and tested in one place.
Performance, security and maintenance risks
The most serious risk is catastrophic backtracking, in which nested quantifiers such as (a+)+$ force a backtracking engine to explore an exponential number of paths. When an attacker controls the input, this becomes a regular expression denial of service (ReDoS) that can freeze a server thread for seconds or minutes.
- Avoid nested quantifiers over overlapping character sets, and prefer specific classes such as
[^"]*to a generic.*. - Set match timeouts where the platform offers them, or use a linear-time engine for untrusted input.
- Anchor validation patterns with
^and$so that partial matches are not accepted as valid input. - Escape user-supplied text before inserting it into a pattern, because characters such as
.and+carry meaning. - Document complex patterns with verbose mode or comments and cover them with unit tests, including failing cases.
Maintainability is the quieter problem. Dense patterns are easy to write and hard to read later, so teams benefit from splitting long expressions into named pieces, keeping a set of positive and negative test strings, and reviewing every change to a shared pattern as carefully as any other error-prone code path.
Put simply
A regular expression is a search rule written in a short code. It does not look for one exact word. It describes the shape of what you want. An example is “three digits, a dash, then four digits”.
It works like a stencil laid over a long text. Wherever the text fits the stencil, the computer marks a match. The same stencil can check whether a form entry is valid. It can also pull out every date from a report or replace old names with new ones. Very clever stencils become hard for people to read. That is why simple and well-tested patterns are best.
In practice
An operations engineer at a mid-sized online retailer needs to find why checkout requests slowed down overnight. The web servers produced about 4 million log lines, each containing a timestamp, an HTTP method, a path, a status code and a response time in milliseconds.
The engineer writes one pattern with named groups for the path, the status and the duration, then filters for responses slower than 2,000 ms on paths starting with /checkout. A short script compiles the pattern once, scans the logs in under a minute and groups the slow requests by path.
The result shows that 92 percent of slow requests hit a single payment-confirmation endpoint after a configuration change at 01:40. Before adding the pattern to the team monitoring toolkit, the engineer runs it against a file of malformed lines to confirm that it fails quickly instead of backtracking, which keeps the toolkit safe against unexpected input.