What Is Regex?

A regular expression—usually shortened to regex—is a compact pattern that describes text. Software can use that pattern to find, extract, split, replace, or perform an initial format check on character sequences.

For example, the pattern error finds those literal letters, while error\s+\d+ can find the word error, one or more whitespace characters, and one or more digits. Regex is best treated as a small language for answering: what shape of text am I looking for?

Read a Pattern from Left to Right

Start with a concrete example. This pattern matches an entire value such as INV-2048:

^INV-[0-9]{4}$
PartMeaning
^Begin at the start of the text.
INV-Match these literal characters.
[0-9]Match one digit from 0 through 9.
{4}Require the preceding digit class exactly four times.
$Finish at the end of the text.

Without the anchors, the engine may find INV-2048 inside a longer value. With both anchors, the complete input must follow the pattern.

Regex Flavours Matter

The core ideas are widely shared, but regex is not identical everywhere. JavaScript, Python, .NET, Java, PCRE, POSIX tools, and text editors may differ in supported features, escaping rules, flags, and Unicode behaviour.

Before using an advanced feature such as lookbehind, named groups, or Unicode properties, check the documentation for the exact language or tool running the pattern.

Core Matching Symbols

PatternMeaningExample
textMatches literal characters.cat matches cat.
.Matches almost any single character; newline behaviour depends on the flavour and flags.c.t matches cat and cut.
[abc]Matches one listed character.Matches a, b, or c.
[a-z]Matches one lowercase character in a range.[A-Z] selects uppercase letters; [0-9] selects ASCII digits.
[^0-9]Matches one character not in the set.Selects one non-digit character.
^Anchors the match at the start of the string or line.^GET
$Anchors the match at the end of the string or line.\.log$
|Matches the expression on the left or right.error|warning
\Escapes a special character or begins a shorthand class.\. matches a literal dot.

Useful Shorthand Classes

PatternCommon meaningOpposite
\dA digit. Unicode or ASCII behaviour can vary by flavour.\D
\wA word character, often a letter, digit, or underscore—not any arbitrary character. The exact Unicode set varies.\W
\sA whitespace character such as a space, tab, or newline.\S
\bA position at a word boundary; it consumes no character.\B

Use an explicit class such as [0-9] when the requirement is specifically an ASCII digit. Shorthand classes are convenient, but their meaning may be broader than expected.

Quantifiers Control Repetition

A quantifier applies to the item immediately before it: one character, one character class, or one group.

QuantifierMeaningExample
*Zero or more.ab* matches a, ab, or abbb.
+One or more.ab+ requires at least one b.
?Zero or one.colou?r matches color and colour.
{n}Exactly n.[0-9]{4}
{n,}At least n.\w{3,}
{n,m}Between n and m.[A-Z]{2,5}

Groups, Captures, and Alternation

Parentheses group several tokens so they can be repeated or treated as one choice. In most flavours, a plain group also captures the text it matched.

(ha)+        matches: ha, haha, hahaha
(cat|dog)    matches: cat or dog
gr(a|e)y     matches: gray or grey
https?       matches: http or https

A non-capturing group such as (?:cat|dog) groups without storing a capture in flavours that support it. Captures are useful when extracting parts of a match or rearranging text during replacement.

Escape Special Characters

When a character such as ., +, (, or ? should be treated literally, place a backslash before it. For example, \. matches a dot, \+ matches a plus sign, and \( matches an opening parenthesis. A programming-language string may require another layer of escaping before the regex engine receives the pattern.

Greedy and Lazy Matching

Quantifiers are usually greedy: they initially take as much text as possible while still allowing the pattern to succeed. Adding ? after many quantifiers makes them lazy, so they take as little as possible.

Text:  "one" and "two"
".*"   one large match
".*?"  two smaller matches in flavours that support lazy quantifiers

For structured markup, a real HTML or XML parser is normally safer than increasingly complicated regex.

Build Patterns Step by Step

A Value That Starts with “h”

Start with ^h to anchor the letter at the beginning. Add .*$ when any remaining characters are acceptable:

^h.*$

The dot normally excludes newline characters unless the regex flavour and its flags change that behaviour. If only word characters may follow, use ^h\w*$ instead. Here, \w does not mean “anything”; it commonly means a letter, digit, or underscore. Because * means zero or more, both patterns match the single value h. Change * to + when at least one following character is required.

Exactly Three Digits

Use a digit class, an exact quantifier, and both anchors:

^\d{3}$

This matches 007 and 365, but not 42 or 12345. Without the anchors, \d{3} can find three digits inside a longer value such as 12345. Some flavours let \d match digits from several writing systems; use ^[0-9]{3}$ when the requirement is specifically three ASCII digits.

A Simplified Email-Like Shape Check

A short pattern can catch obvious formatting mistakes without pretending to implement every rule for an email address:

^[^\s@]+@[^\s@]+\.[^\s@]+$

This requires non-whitespace text on both sides of @ and a dot later in the domain. It allows common characters such as periods and hyphens, but can still accept invalid addresses and reject unusual valid ones. Treat it as a basic user-interface check—not an RFC-complete validator or proof that the address exists. Application-level validation and a confirmation message are more reliable.

Common Flags

PurposeTypical flagEffect
Case-insensitiveicat can also match Cat.
GlobalgFinds all matches rather than only the first in tools that use this flag.
MultilinemChanges how ^ and $ treat line boundaries.
Dot matches newlinesAllows . to include newline characters.

Flag names and availability vary, so check the host tool's syntax.

Common Mistakes

  • Forgetting anchors when the whole value must match.
  • Using . when a literal dot \. was intended.
  • Applying a quantifier to only one character when a group was intended.
  • Forgetting that the programming language may process backslashes before the regex engine sees them.
  • Assuming the same advanced feature works in every regex flavour.
  • Writing one enormous pattern when simpler string operations would be easier to maintain.

Use Regex Safely

Test both expected matches and expected failures, including empty input and unusually long text. Be cautious with overlapping alternatives and nested repetition such as repeated groups that can match in many different ways; some backtracking engines may take excessive time on crafted input.

Good practice: Keep patterns specific, limit input size, avoid accepting arbitrary user-supplied patterns, and use time limits or a non-backtracking engine when the application processes untrusted data at scale.

Quick Recap

  • Literal characters match themselves; metacharacters add rules.
  • Character classes choose one character, while quantifiers control repetition.
  • Groups combine tokens, capture results, and scope alternatives.
  • Anchors are essential when the entire value must match.
  • Regex flavours differ, especially for advanced features and Unicode.
  • The clearest maintainable solution is better than the shortest pattern.