Regex AND: Matching Multiple Conditions in One Regular Expression

Regular expressions have no AND operator. This guide explains how lookaheads and set intersection fill the gap, where they work, and when separate checks are better.

Regular expressions have an OR operator, the vertical bar, but no AND operator. When people search for a regex AND, they usually want one pattern that matches only if several conditions hold at once. For example, a line must contain both "red" and "blue" in any order, or a password must contain both a digit and an uppercase letter. This review covers the techniques that do this, what each one actually does to the match, and when separate checks are the better choice.

Short answer: is a regex AND suitable for your use?

Use a single AND-style pattern when you can supply only one regex and the engine supports lookahead. Typical cases are a validation field, a configuration setting, an editor search box, or a filter rule. The benefit is that order-independent conditions fit in one expression. The cost is that the pattern is harder to read and maintain, and it does not work in every regex engine.

Prefer separate checks in these situations:

  • You control the surrounding code and can test each condition separately.
  • The conditions are literal words, so a plain substring check is clearer than a regex.
  • The pattern must run on engines without lookaround, such as POSIX grep, Go's regexp, or Rust's regex crate.
  • The number of conditions is large or likely to grow.

Why regex has OR but no AND

A regex engine reads the input from left to right and consumes characters as it matches them. Alternation (a|b) fits this model because only one branch has to succeed at a given position. An AND condition is different. It asks whether several patterns can each match somewhere in the same text, regardless of order. Sequential matching cannot express that directly.

There are three common workarounds:

  • Lookaheads: order-independent conditions on the same text.
  • Alternation over every ordering: works in engines without lookaround, but only for a few terms.
  • Character class intersection: AND applied to sets of characters rather than to whole patterns.

Method 1: lookaheads

A positive lookahead, written (?=...), checks whether its contents could match starting at the current position. It does not consume any characters. Because each lookahead leaves the position where it was, you can stack several of them at the start of the string. Each one then scans the same text independently.

^(?=.*\bred\b)(?=.*\bblue\b).*$

Here is how the pattern works:

  • The ^ anchors the match at the start of the string.
  • The first lookahead requires the word "red" somewhere in the text.
  • The second lookahead requires the word "blue" somewhere in the text.
  • The trailing .*$ is optional. Include it only if you need the full text as the match result. Without it, the pattern still returns a zero-length match when both conditions hold.

Here is how the pattern handles some sample lines:

red and blue      -> match
blue then red     -> match (order does not matter)
red only          -> no match (no "blue")
reddish blue      -> no match (\b stops "red" from matching inside "reddish")

The word boundaries (\b) matter. Without them, (?=.*red) would also accept "reddish" or "bored". If partial words should count, remove them.

The same structure is often used for password rules. The following pattern requires at least one uppercase letter, at least one digit, and a minimum length of eight characters:

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

A negative lookahead, written (?!...), adds a NOT condition. For example, ^(?=.\bred\b)(?!.\bgreen\b) matches text that contains "red" and does not contain "green".

Method 2: alternation over every ordering

If the engine has no lookahead, you can list each possible order explicitly:

red.*blue|blue.*red

This works for two terms. However, the number of branches equals the number of possible orderings. Three terms need six branches, and four terms need twenty-four. Beyond two or three conditions, chaining separate searches is clearer and less error-prone.

Method 3: character class intersection

Some engines support AND within a character class. For example, "a lowercase letter that is not a vowel" can be written as an intersection of two sets:

  • Java: [a-z&&[^aeiou]] uses the documented && intersection syntax.
  • JavaScript: the v (unicodeSets) flag, added in ES2024, supports && intersection inside a class. Older engines and patterns without the v flag do not.
  • Python's built-in re module does not support class intersection.

Intersection applies to single characters only. It cannot require two words or two sub-patterns to appear in the same text, so it does not replace lookaheads for that purpose.

What an AND pattern changes, and what it doesn't

A regex used for matching never alters the input text. It only reports whether a match exists and which span it covers. With lookaheads, the conditions themselves are zero-width and contribute no characters to the match. This matters most in search-and-replace.

If the pattern is only ^(?=.red)(?=.blue), the match is empty. Replacing it inserts text at the start of the line and deletes nothing. To replace a whole line, add . or .$ after the lookaheads. To replace one specific word, put that word outside the lookaheads and keep the other conditions inside them.

Line handling is another source of surprise. By default, the dot does not match newline characters, and ^ and $ refer to the start and end of the whole input. To test each line separately, enable multiline mode (the m flag, or re.MULTILINE in Python). To let a condition match across line breaks, enable dot-all mode (the s flag, or re.DOTALL in Python). Without dot-all mode in JavaScript, you can use [\s\S] in place of the dot.

Portability: will the pattern work in other tools?

A pattern that works in one tool can fail when copied into another. It may raise a syntax error, or it may match differently without warning you. Lookaround support is the main dividing line. The table below reflects documented behavior. Check the documentation for the specific version you use, because support changes between releases.

Engine or tool | Lookahead (?=...) | Notes
PCRE / PHP / grep -P | Yes | grep -P is available in GNU grep only
Java | Yes | Also supports class intersection with &&
JavaScript | Yes | Class intersection requires the v flag
Python re | Yes | No class intersection
.NET | Yes |
POSIX ERE (grep -E, many sed and awk versions) | No | Use chained searches instead
Go regexp (RE2) | No | Lookaround is excluded by design
Rust regex crate | No | Lookaround is excluded by design

Where lookahead is unavailable, chaining two searches gives the same AND result for line-based filtering, and any POSIX shell supports it:

grep -w red file.txt | grep -w blue

In application code, a separate test for each condition is usually the clearest form:

import re

conditions = [r"\bred\b", r"\bblue\b"]
matches = all(re.search(p, line) for p in conditions)

Readability and maintenance

Stacked lookaheads become hard to read quickly. A reviewer has to recognize that each group is an independent condition and not part of a sequence. Engines with a verbose or extended mode let you put each condition on its own line with a comment. This is the x flag in PCRE and re.VERBOSE in Python. JavaScript has no equivalent flag. If no one on the team is familiar with lookarounds, separate checks with descriptive names are easier to maintain.

pattern = re.compile(r"""
    ^
    (?=.*[A-Z])   # at least one uppercase letter
    (?=.*\d)      # at least one digit
    .{8,}$        # minimum length 8
""", re.VERBOSE)

Performance

Each lookahead that begins with .* scans forward from the anchor, so the input is read once per condition. Anchoring with ^ is important. Without an anchor, the engine retries the whole set of lookaheads at every position in the string after a failure. No benchmark data was available for this review. If you apply these patterns to large files or untrusted input, measure them in your own engine. Also avoid nested quantifiers inside the lookaheads, because they can cause excessive backtracking.

Gaps in this review

The engine-support statements reflect documented behavior. They were not verified by tests across specific tool versions. Online regex testers, IDE search boxes, and hosted filter fields may use a different engine than the label suggests, or a restricted subset of one. Before relying on a lookahead pattern there, confirm which engine the tool uses.