What is a Regular Expression (regex)? A practical guide
A regular expression (regex or regexp) is a sequence of characters that forms a search pattern for matching and manipulating text. Built on a formal mathematical foundation and common to almost every programming language and tool, regex lets you validate input, find and replace text, extract data, and transform strings with a compact, declarative syntax. This guide explains what regex is, its core syntax, how it is implemented, and how to use it safely.
On this page
- What problems does regex solve?
- Core regex syntax
- Two major families: POSIX and Perl-compatible
- Using regex in JavaScript
- Pitfalls and safe use
- FAQ
- What is a regular expression (regex)?
- Where are regular expressions used?
- What is the difference between POSIX and PCRE regex?
- Why should I escape special characters in a regex?
A regular expression (regex or regexp) is a sequence of characters that forms a search pattern for matching and manipulating text. Regex lets you validate input, find and replace text, extract data, and transform strings with a compact, declarative syntax rather than writing long procedural search logic. The concept was formalized in the 1950s by the mathematician Stephen Kleene for the theory of regular languages, and it came into common use with Unix text-processing utilities; today nearly every programming language and many tools support some dialect of it.
What problems does regex solve?
Without regex, checking whether a phone number is valid, extracting every URL from a document, or renaming a set of files by pattern requires multiple statements, loops, and hand-written comparison logic. A regex collapses that into one pattern:
- Validate input — check whether an email, phone number, or postal code matches an expected shape.
- Find and extract — pull every log line, ID, or URL matching a pattern out of a larger text.
- Search and replace — rename or transform text consistently, using captured groups to reuse parts of a match.
- Split text — break a string into pieces at any point that matches a pattern.
Because it is declarative, the same pattern can be reused across languages and tools once you account for dialect differences.
Core regex syntax
A regex is built from literal characters and metacharacters that carry special meaning:
- Literals — ordinary characters match themselves.
/abc/matches the exact sequenceabcin order. - Character classes —
[abc]matches any one ofa,b, orc;[^abc]matches any character that is not one of those; a range such as[a-z]matches any lowercase letter. - Shorthand classes —
\dmatches any digit,\wany word character,\sany whitespace; their uppercase forms (\D,\W,\S) match the negation. - Quantifiers —
*means "zero or more of the preceding item",+means "one or more",?means "zero or one", and{n,m}means "between n and m". - Anchors and assertions —
^anchors to the start of the string (or line with the multiline flag),$to the end;\bmarks a word boundary; look-ahead and look-behind assert conditions without consuming characters. - Groups and alternation — parentheses
( )group a subpattern and capture its match for later reuse (backreference);|means alternation ("or").
For example, the pattern /^a.c$/ matches a string that starts with a, then any one character, then ends with c — like abc or aXc, but not ac or abbc.
Two major families: POSIX and Perl-compatible
Regex dialects broadly fall into two families:
- POSIX — the POSIX standard defines Basic Regular Expressions (BRE) and Extended Regular Expressions (ERE). ERE adds
+,?, and|, and treats( )and{ }as metacharacters without escaping; BRE requires them to be escaped (\(and\{). GNU tools likegrepexpose these modes (grep -Efor ERE,grep -Gfor BRE by default). - Perl-compatible (PCRE) — beginning in 1997, Philip Hazel built PCRE to closely mimic Perl's richer regex features. It added non-greedy matching, look-around assertions, backreferences, named groups, and recursion. Because of that expressive power, Perl-like syntax became a de facto standard adopted by JavaScript, Java, Python, Ruby, PHP, and many other languages and tools.
The differences matter in practice: a pattern that is valid in one dialect may fail or behave differently in another, so always test patterns in the specific environment you are working in.
Using regex in JavaScript
In JavaScript, a regex is an object. You create it with a literal (a pattern between slashes) or with the RegExp constructor:
const re = /ab+c/;— a literal, compiled once when the script loads (faster for fixed patterns).const re = new RegExp("ab+c");— the constructor, compiled at runtime (useful when the pattern comes from user input or changes).
You then use it with the RegExp methods test() and exec(), or with the String methods match(), matchAll(), replace(), replaceAll(), search(), and split(). To test whether a string contains a match, use test():
const emailLike = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailLike.test("hello@debod.id"); // true
Flags tune behavior: g for a global search, i for case-insensitive, m to make ^ and $ match per line, s to let . match newlines, and u to treat the pattern as Unicode code points (enabling Unicode property escapes like \p{L}).
Pitfalls and safe use
Regex is powerful but easy to misuse:
- Catastrophic backtracking — patterns with nested quantifiers over overlapping alternatives can take exponential time on certain inputs, a classic denial-of-service vector. Keep patterns simple, and avoid deeply nested quantifiers when matching untrusted input.
- Dialect differences — escaping rules differ; in POSIX BRE, for example,
(and{must be escaped to be metacharacters, while in ERE and Perl-like syntax they are metacharacters by default. - Escape special characters — when you need a literal
*,., or/, escape it with a backslash (/a\*b/), or wrap it in a character class (/a[*]b/). In aRegExpstring literal, backslashes must themselves be escaped so the pattern survives string escaping. - Test before shipping — because dialects vary, always validate a pattern against real inputs in the exact tool or language, not just in an online tester.
When you need to validate input, prefer the simplest pattern that works, combine it with normalization at the boundary (trimming, length checks), and treat untrusted strings as data — never execute user-supplied patterns as code.
FAQ
What is a regular expression (regex)?
A regular expression, or regex for short, is a sequence of characters that forms a search pattern for matching text. It lets you validate input, find and replace strings, extract data, and transform text with a compact declarative syntax instead of writing long search logic by hand.
Where are regular expressions used?
Regular expressions appear in almost every programming language (JavaScript, Python, Java, Ruby, PHP, and more) and in many developer tools, including code editors for find-and-replace, command-line tools like grep and sed, and API testing and issue-tracking platforms. The concept dates to the 1950s with Stephen Kleene's work on regular languages and became common through Unix text-processing utilities.
What is the difference between POSIX and PCRE regex?
POSIX defines Basic (BRE) and Extended (ERE) regex, where ERE adds +, ?, and | and makes ( ) and { } metacharacters without escaping. PCRE (Perl Compatible Regular Expressions), started in 1997, closely mimics Perl's richer feature set, adding non-greedy matching, look-around assertions, backreferences, named groups, and recursion, and it became a de facto standard adopted by many modern languages.
Why should I escape special characters in a regex?
Metacharacters like *, ., ?, (, and / carry special meaning, so matching them literally requires a backslash (/a\*b/) or a character class (/a[*]b/). In JavaScript's RegExp("...") constructor, backslashes must also be escaped to survive string escaping — otherwise the pattern changes meaning.
Sources
- MDN — Regular expressions (developer.mozilla.org
- CC-BY-SA 2.5+)
- Wikipedia — Regular expression (en.wikipedia.org
- CC BY-SA 4.0)
- Wikipedia — PCRE (en.wikipedia.org
- CC BY-SA 4.0)
Share this guide
Related guides
- What is Object-Oriented Programming (OOP)? A complete guide
Object-oriented programming is a paradigm based on objects that combine data and behavior. Learn the four pillars — encapsulation, inheritance, polymorphism, and abstraction — with practical examples and how they work in JavaScript, Java, and Python.
- What is WebAssembly (WASM)? How it works and when to use it
WebAssembly is a binary instruction format for a stack-based virtual machine — a portable compilation target that lets you run C, C++, Rust, and other compiled languages in the browser and beyond. Here's how it works and when it's worth using.
- Open source licenses explained: MIT, Apache, and GPL compared
Open source licenses decide how others can use, modify, and distribute your code. This guide explains permissive licenses (MIT, Apache 2.0), copyleft licenses (GPL, AGPL), and how to choose the right one for your project.