Regex matching basics and patterns

How regex matching works: core pattern syntax, greedy vs lazy matching, Unicode pitfalls, copying patterns between engines, and when plain string methods are better.

A regular expression, or regex, is a compact pattern that describes a set of strings. A regex engine scans input text and reports where that pattern matches, and can optionally capture parts of the match or replace them. This overview covers what a regex match does and does not change, the building blocks most patterns use, the behaviors that commonly surprise people, and the situations where regex is the wrong tool.

What a regular expression means in practice

A pattern describes the shape of text, not its meaning. A match is a read-only operation. The engine returns whether the pattern was found, where it starts and ends, and the text captured by any groups. The input is never altered. Text changes only when you run a replace operation, and even then most languages return a new string rather than modifying the original. Your stored data stays the same until your own code writes the result back. Keeping search and replace separate is the main safeguard in any regex-based transformation workflow.

Core pattern building blocks

Construct | Example | What it matches
Literal characters | cat | The exact sequence c, a, t
Dot | c.t | Any single character between c and t (by default, not a newline)
Character class | [aeiou] | One character from the listed set
Negated class | [^0-9] | One character that is not an ASCII digit
Shorthand classes | \d \w \s | Digit, word character, whitespace (exact sets vary by engine and flags)
Quantifiers | a* a+ a? a{2,4} | Zero or more, one or more, optional, between two and four
Anchors | ^ $ \b | Start of input or line, end of input or line, word boundary
Groups | (ab)+ | Treats ab as one unit and captures it
Alternation | cat|dog | Either cat or dog
Escaping | . | A literal dot instead of any character

Shorthand classes are a common source of drift between environments. In some engines and modes, \d and \w match only ASCII characters. In others, they also cover digits and letters from other scripts. If the difference matters, use an explicit class such as [0-9].

A short regex tutorial workflow

  • Start with a literal piece of the text you want and confirm it matches.
  • Replace the variable parts with character classes and quantifiers one at a time.
  • Add anchors or word boundaries so the pattern cannot match inside unrelated text.
  • Test against examples that should match and examples that should not.
  • Include edge cases: empty input, extra whitespace, line breaks and non-ASCII characters.
  • Only then wire the pattern into code or a replace operation.

Matching behavior that surprises people

Quantifiers are greedy by default. They take as much text as possible and give back only what the rest of the pattern needs. Adding ? after a quantifier makes it lazy, so it takes as little as possible.

Input:    <b>bold</b>

Pattern:  <.+>
Match:    <b>bold</b>        (greedy: one match spanning both tags)

Pattern:  <.+?>
Matches:  <b>  and  </b>     (lazy: each tag separately)
  • Search versus full match: many APIs look for the pattern anywhere in the input unless you anchor it. In Python, re.match anchors only at the start, while re.fullmatch requires the whole string to match.
  • Line anchors: without a multiline flag, ^ and $ usually refer to the whole input, not each line.
  • The dot and newlines: in most engines the dot skips newline characters unless a dotall or single-line flag is set.
  • Case sensitivity: matching is case-sensitive by default. Case-insensitive flags may treat non-ASCII letters differently across engines.
  • Shape is not validity: a pattern can confirm a format but not whether the value makes sense.
Pattern:  ^\d{4}-\d{2}-\d{2}$

2026-10-31   match
9999-99-99   match     (right shape, not a real date)
2026-1-31    no match  (month has one digit)

What a regex match changes, and what it doesn't

Matching changes nothing. A replace operation changes stored characters in the output string. Regex has no visual-only effect, unlike CSS styling or bidirectional display. Whatever a replacement produces is the actual text that gets copied, saved or indexed. Before trusting a replace over real data, preview the matches. Spans that look correct on screen can contain characters you did not expect.

Unicode is where patterns most often miss. A regex engine works on code points, or in some modes on UTF-16 code units. It does not work on what a reader perceives as a single character. The same visible letter can be stored in more than one way, so a literal pattern can fail on text that looks identical.

Pattern:  café

Input 1:  c a f U+00E9            match
Input 2:  c a f e U+0301          no match

Input 2 uses a plain e followed by a combining acute accent.
Normalizing both pattern and input (for example to NFC) makes them comparable.

Emoji show the same gap. A family or profession emoji is often several code points joined by the zero width joiner (U+200D). A dot in Unicode mode matches only one of those code points, so a replacement can split the emoji into fragments. In JavaScript without the u flag, a dot can match half of a surrogate pair. Some engines, such as PCRE and Perl, offer \X to match a full grapheme cluster. Where that is unavailable, handle user-perceived characters with a dedicated text segmentation library.

Copying and sharing patterns between tools

A pattern that works in an online tester can break when you paste it elsewhere. There are three usual causes: flavor differences, string escaping, and invisible characters picked up during copying.

  • Flavors differ: PCRE, JavaScript, Python, Java, .NET, POSIX and RE2 support different features. RE2, for example, omits backreferences and lookaround. POSIX classes use forms like [[:digit:]] instead of \d.
  • Delimiters are not part of the pattern: the slashes and trailing flags in /abc/gi are JavaScript literal syntax.
  • String literals add a layer of escaping: each backslash in the pattern may need to be doubled inside a normal string.
  • Copied text can carry curly quotes, non-breaking spaces or zero-width characters that silently change the pattern.
Pattern as typed in a tester:      \d+\.\d+
Python raw string:                 r"\d+\.\d+"
Java or C# regular string:         "\\d+\\.\\d+"
JavaScript regex literal:          /\d+\.\d+/

Readability is a usability limit in its own right. Long patterns are hard to review and easy to break during edits. Several engines, including PCRE, Perl, Python, Java and .NET, support a verbose or extended mode where whitespace is ignored and comments are allowed. JavaScript has not traditionally offered this, so check your engine's documentation. When a pattern enforces input rules in a form, describe the expected format in plain language as well. The pattern itself means little to most people, including those using assistive technology. No specific browser or screen reader behavior was tested for this article.

Performance caveat: catastrophic backtracking

Most popular engines find matches by backtracking. Nested quantifiers that can split the same text in many ways can force the engine to try an exponential number of paths when a match ultimately fails. With untrusted input, this becomes a denial-of-service risk. Engines built on automata, such as RE2 and Rust's regex crate, guarantee linear-time matching by design. The cost is giving up backreferences and lookaround.

Risky:  ^(a+)+$
Input:  aaaaaaaaaaaaaaaaaaaaaaaaaaaa!

The trailing ! guarantees failure, and a backtracking engine
explores many ways to divide the a's before giving up.
Safer:  ^a+$

Is regex suitable for your use?

Regex fits finding and checking the shape of text: log lines, identifiers, simple formats, and bulk search-and-replace where you can preview matches first. Its main benefit is expressing a flexible pattern in one compact line. The decisive tradeoff is that the line is hard to read, varies between engines, and handles Unicode text by code points rather than visible characters.

Plain string methods are preferable when you are looking for a fixed substring, prefix or delimiter. Contains, starts-with and split are clearer and avoid escaping mistakes. A real parser is preferable for nested or structured formats such as HTML, JSON or quoted CSV. Dedicated validation libraries are preferable for email addresses, URLs and dates, where the real rules are far more complex than a readable pattern can express.

Gaps in this overview

No specific regex tester, library version or destination application was evaluated. No performance measurements were taken. The behaviors described are general documented properties of common regex engines, and details change between versions and flags. Before relying on a pattern, confirm it against your engine's documentation and test it on representative input, including non-ASCII text and examples that should fail.