← Back to blog

Regex Lookahead: Positive and Negative Syntax, Examples

October 29, 2026
Regex Lookahead: Positive and Negative Syntax, Examples

A regex lookahead checks what comes next in the text without making it part of the match. Write (?=...) for a positive lookahead (the text must follow) and (?!...) for a negative lookahead (the text must not follow). The engine peeks ahead, reports yes or no, and stays where it was. This guide shows how each form behaves, walks through patterns you will use in real code, and covers the traps that make lookaheads look broken.

Pingfloat
Check Regex Before You Ship
Pingfloat offers web tools for developers, including JSON validation utilities, alongside uptime monitoring, SSL checks, and network diagnostics.
Explore Pingfloat tools

TL;DR

  • A lookahead is a zero-width assertion: it tests the text to the right of the current position and consumes nothing, so the tested text never appears in the match.
  • Positive lookahead is (?=pattern). Negative lookahead is (?!pattern). Both put the condition after the text you want to return.
  • Stack several lookaheads at the start of a pattern to require multiple conditions at once, as in password rules.
  • (?!foo)bar does not mean "bar not preceded by foo". Conditions about preceding text need a lookbehind.
  • The basic syntax is the same in most engines that support lookahead, so test your pattern in the engine you will actually deploy to.

Table of Contents

What a lookahead does

A regular expression normally moves forward as it matches. Every character it matches is consumed and ends up in the result. A lookahead breaks that rule. According to MDN's reference, it tests whether a pattern can match immediately to the right of the current position, then accepts or rejects the match without consuming the text it tested.

That gives you two practical effects:

  1. A filter. The match is only valid if the condition holds.
  2. A clean result. The condition text is not captured, so you do not have to strip it off afterward.

The family is called lookaround. Lookahead looks right, lookbehind looks left. Jan Goyvaerts, author of a long-running regex tutorial, explains that lookaround is useful because it expresses conditions that would otherwise be impossible, or would need much longer expressions.

Positive lookahead: (?=...)

A positive lookahead succeeds when the pattern inside it matches at the current position. The position does not move afterward. MDN's own example is q(?=u): it matches a q only when a u follows, and the u is not part of the match.

Put the text you want back first, then the required follower in the lookahead:

First(?= test)

With the global flag, MDN shows this returning First (but not test) in "First test", and finding nothing in "First peach" (MDN, Assertions).

A practical example: words before a semicolon

The PHP Manual gives \w+(?=;) as a typical case. It matches a word only when a semicolon follows, and the semicolon stays out of the match (PHP Manual: Assertions). Run it on a=1; b=2; c and it returns 1 and 2, because those are the word runs directly followed by a semicolon. The final c has nothing after it, so it is skipped.

Alternation and groups inside a lookahead

The lookahead can hold any valid regular expression. MDN shows /Jack(?=Sprat|Frost)/ matching Jack when it is followed by either Sprat or Frost, with neither suffix included (MDN, Assertions). Lookaheads may also contain capturing groups, which is how you pull out a value that sits ahead of your match without moving past it.

Negative lookahead: (?!...)

A negative lookahead succeeds when its inner pattern does not match at the current position. MDN documents the syntax as (?!pattern).

Place the forbidden follower after the text you want to keep. MDN's example is /\d+(?!\.)/, which matches a number only if it is not followed by a decimal point. On 3.141 it matches 141, not 3 (MDN, Assertions).

That result surprises people. Why does 141 match? Because \d+ is allowed to match fewer digits. On 3, the next character is a dot, so the lookahead rejects it. The engine then moves on, and 141 has no dot after it, so that run passes.

If you wanted to reject the whole decimal number, add a boundary or consume the digits first: \b\d+\b(?!\.\d) is one way, and testing it against your real input will tell you whether it fits.

Side by side

FeaturePositive lookaheadNegative lookahead
Syntax(?=pattern)(?!pattern)
Succeeds whenThe pattern matches aheadThe pattern does not match ahead
Consumes textNoNo
Typical useRequire a suffix or a conditionExclude a suffix or a value
Exampleq(?=u)\d+(?!\.)

Patterns you will actually use

The examples below are written in JavaScript syntax, but the lookahead parts work the same way in most engines. You can paste any of them into our free regex tester to see live matches as you edit.

1. Stacking lookaheads: password rules

Because a lookahead consumes nothing, you can place several at the same position. Each one checks a different condition against the whole string, starting from the beginning:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$

Read it left to right. At the start of the string, the first lookahead requires a digit somewhere ahead, the second a lowercase letter, the third an uppercase letter. Then .{8,} actually consumes the string and enforces a minimum length of eight. Without lookaheads you would need to list every ordering of digit, lower and upper case, which is why this is the classic use case.

Three password checks followed by a length rule

One caution: composition rules like this are a UI convenience, not a security measure. Use the regex to give users quick feedback, and enforce your real policy on the server.

2. Adding thousands separators

A well-known trick inserts commas into a long number:

"1234567".replace(/\B(?=(\d{3})+(?!\d))/g, ",");
// "1,234,567"

The pattern matches an empty position (not a character) where the digits remaining to the right form complete groups of three. The negative lookahead (?!\d) anchors the end of the digit run. Because the match is zero-width, the replacement simply inserts a comma at that spot. In production, Intl.NumberFormat is usually the better choice for display, since it handles locale differences, but the regex is a good way to see lookahead at work.

3. Excluding file types

Say you want every filename except temp files. A negative lookahead at the start tests the whole string before any matching begins:

^(?!.*\.tmp$).+$

It rejects report.tmp and accepts report.pdf. This pattern shape, ^(?!...), is the standard way to say "the string must not contain or end with X".

4. Matching a word only in one context

foo(?!bar) finds foo unless bar comes right after it. So foobaz matches, foobar does not. In a log-cleaning job you might use error(?!_handled) to find error lines that were not tagged as handled.

5. Validating input shapes

Lookaheads are common inside bigger validators, such as requiring that an address has a domain part before you check its characters. Email is a good example of both the usefulness and the limits of regex, and we cover it in our email regex validation guide.

The mistake that catches everyone: lookahead is not lookbehind

The PHP Manual warns about a common misreading: (?!foo)bar does not mean "bar not preceded by foo". It can match any bar, because the assertion is evaluated at the position where bar would start, and at that position the next characters are bar, not foo (PHP Manual: Assertions). The manual says a lookbehind is needed for a condition on preceding text.

The rule to remember: a lookahead tests what begins at the current position. It cannot see what the engine has already passed. If your requirement is about text on the left, switch to a lookbehind such as (?<!foo)bar, and check that your engine supports it, since lookbehind support and limits vary more than lookahead does.

Engine differences that matter

The basic syntax, (?=regex) and (?!regex), is the same across engines that support lookahead. The cross-engine reference notes the main portability issue is whether an engine supports it at all, not how positive and negative forms are written. Perl-style engines, PCRE (used by PHP), .NET and JavaScript all handle the common cases.

A subtler difference is backtracking. MDN notes that JavaScript does not backtrack into a lookahead to revise a choice made inside it. Once the lookahead has succeeded with a particular capture, the engine will not go back and try another way to satisfy it, even if the rest of the pattern fails. If you rely on captures inside a lookahead, test the unusual inputs.

The practical advice: write the pattern in the language you will ship in, and test it there. A pattern that works in one tester may behave differently in another engine's flags or Unicode handling.

How to debug a lookahead that will not match

When a lookahead misbehaves, work through these checks in order:

  1. Check the position. Remember the lookahead tests text starting at the current position. a(?=b) tests the character right after a, not anywhere later.
  2. Add .* when you mean "somewhere ahead". (?=\d) means a digit is next. (?=.*\d) means a digit appears somewhere ahead on the line.
  3. Anchor it. For whole-string conditions, start with ^ so the lookahead runs once from the start rather than at every position.
  4. Mind the flags. Without the s flag in JavaScript, . does not cross line breaks, so (?=.*\d) only scans the current line. Add the m flag when ^ and $ should match at each line.
  5. Shrink the pattern. Remove everything except the lookahead and one literal. Add pieces back until it breaks.
  6. Watch for catastrophic backtracking. Nested quantifiers inside a lookahead, such as (?=(a+)+b), can run extremely slowly on long non-matching input. Keep the inside simple.

Our perspective

We build developer tools, and regex questions are among the most common things people bring to a tester. The pattern we see most is not a clever one. It is a lookahead that looked right in the head and did something else on real input: a . that stopped at a line break, a negative lookahead placed on the wrong side of the token, or a pattern tested only on the happy path.

Our perspective — overview diagram

Our advice is to treat lookahead as a precision tool, not a default. If a plain pattern with a capture group does the job, use it, because the next person reading it will thank you. Reach for lookahead when you need one of three things: several conditions on the same text, a match that must not include its context, or an exclusion that would otherwise need a long list of alternatives.

And always test with both inputs that should match and inputs that should not. Lookahead bugs hide in the second group. Keep a short list of near-misses next to the pattern, such as First peach for First(?= test), and rerun them whenever you change anything.

— Andreas

Try your lookahead before you ship it

The fastest way to understand a lookahead is to watch it accept and reject text as you type. Our JavaScript regex tester shows live matches with no install and no account, so you can paste a pattern from this article, change the lookahead and see what moves.

Pingfloat

When you are ready, open the regex tester. The rest of the free toolkit sits on the Pingfloat home page, including a JSON formatter, a Base64 encoder and decoder and a JWT decoder, which tend to come up in the same debugging sessions.

FAQ

What is the difference between positive and negative lookahead?

A positive lookahead, (?=...), succeeds only if the pattern inside matches next. A negative lookahead, (?!...), succeeds only if it does not. Neither one consumes characters, so the tested text never appears in the match.

Does a lookahead become part of the match?

No. That is the main reason to use one. In q(?=u), the match is only q, even though a u had to be there for it to succeed. If you need the following text too, capture it with a normal group or a capturing group inside the lookahead.

Can I put more than one lookahead in a pattern?

Yes. Lookaheads are zero-width, so several can sit at the same position and each checks its own condition. That is how password-style rules such as "a digit, a lowercase letter and an uppercase letter" are built, as in ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$.

How do I check text before a match instead of after it?

Use a lookbehind, written (?<=...) for positive and (?<!...) for negative. A lookahead cannot do this: (?!foo)bar does not mean "bar not preceded by foo". Check your engine's lookbehind support first, because it is less uniform than lookahead.

Why does my negative lookahead still match part of the text?

Because quantifiers can match fewer characters. With \d+(?!\.) on 3.141, the engine rejects 3 but accepts 141. Add a word boundary or extend the lookahead so it covers what you actually want to exclude, then test with real samples.

Sources