Regular Expression AND: How to Require Several Conditions in One Pattern
Regex has no AND operator. Learn how lookaheads, ordered patterns and separate checks combine conditions, where each fails, and when plain logic is the better choice.
Regex has no AND operator, so you have to build one
Most regular expression flavors give you alternation, written with the vertical bar, to mean "this or that." None of the common ones has an operator that means "this and that." People searching for how to combine regular expressions with AND usually want one of three things. The first is a line or string that contains several terms in any order. The second is terms that appear in a fixed order. The third is a single character that satisfies two class rules at once. Each of these has a different answer, and each answer has its own limits.
Short verdict: when a single AND pattern is the right tool
A lookahead-based AND pattern suits cases where you can only supply one regex. Examples include a form validation attribute, a configuration field, a log filter or a search box. Its main benefit is that the conditions are independent of order, and you can add or remove them one at a time. The decisive tradeoff is portability. Several widely used engines do not support lookaround at all, and patterns get harder to read as conditions pile up. If your code or tool lets you run several simple tests and combine the results with ordinary logic, that approach is usually clearer, easier to debug and more portable. In those situations, separate checks are preferable to one clever pattern.
What each technique actually does
Unordered AND with positive lookaheads
A lookahead, written (?=...), checks whether its contents could match starting at the current position. It does not consume any characters. That zero-width behavior is what makes AND possible. You anchor at the start of the string and stack several lookaheads. Each one scans forward independently from the same starting point, and the overall match succeeds only if all of them succeed.
^(?=.*\bred\b)(?=.*\bblue\b).*
Read it left to right. The ^ anchors at the start. The first lookahead asks whether the word "red" appears anywhere ahead. The second asks the same about "blue." Neither lookahead moves the position, so the final .* then matches the line itself. By the documented semantics of lookahead, "the blue car and the red bike" satisfies both conditions and matches, while "a red car" fails the second lookahead and does not match. The \b word boundaries stop "red" from matching inside "bored" or "redo." Remove them if partial words should count.
Ordered AND with plain concatenation
red.*blue
If the order is fixed, you don't need lookarounds. This pattern requires "red" followed later by "blue," and it works in essentially every flavor, including POSIX tools. To make it order-independent without lookarounds, you must list every ordering as an alternative. Two terms need two orderings, three terms need six and four terms need twenty-four, because the count is the factorial of the number of terms. Past two or three terms, this approach becomes impractical.
AND NOT with a negative lookahead
^(?=.*\berror\b)(?!.*\btimeout\b).*
A negative lookahead, written (?!...), succeeds only when its contents cannot match ahead. Combined with a positive lookahead, it expresses "contains error but not timeout." Exclusion is often the main reason people reach for lookarounds, because ordinary regex syntax cannot say "this word must be absent from the whole line" any other way.
AND inside a single character class
Sometimes the requirement applies to one character, such as "a lowercase letter that is not a vowel." A few flavors have native syntax for this. Java supports class intersection with &&. .NET supports class subtraction. JavaScript supports intersection inside classes when the v flag is used. Elsewhere, a lookahead before a single character gives the same effect in backtracking engines.
Java: [a-z&&[^aeiou]]
.NET: [a-z-[aeiou]]
JavaScript: /[\p{L}&&\p{ASCII}]/v
Lookahead: (?![aeiou])[a-z]
| Technique | Order of terms | Supports exclusion | Portability | Readability as terms grow |
| Stacked positive lookaheads | Any order | Yes, with negative lookahead | Backtracking engines only | Moderate; one group per condition |
| Concatenation | Fixed order | No | Nearly universal | Good |
| Alternation of all orderings | Any order | No | Nearly universal | Poor beyond two or three terms |
| Separate checks combined in code or a pipeline | Any order | Yes, by negating a check | Universal | Good |
Details that change whether the pattern matches
- Anchoring: without ^, a search function may retry the lookaheads at every position in the string. The final answer is usually the same, but the work increases and the reported match may start mid-line.
- Newlines: in most flavors the dot does not match a line break by default. If the terms can appear on different lines of a multi-line string, enable single-line or dotall mode, for example the s flag in JavaScript or re.DOTALL in Python, or use [\s\S] in place of the dot.
- Line versus string anchors: ^ matches only at the start of the whole string unless multiline mode is on. Choose the mode that fits whether you are testing each line or one block of text.
- Case: lookaheads inherit the pattern's case sensitivity. Add an ignore-case flag if "Red" and "red" should both count.
- Match versus search APIs: some APIs require the whole string to match, such as Java's matches() and Python's re.fullmatch. Others look for a match anywhere, such as Python's re.search and JavaScript's test. A pattern made of lookaheads alone matches an empty span at the start. That is fine for a yes/no search, but a whole-string API needs the trailing .* to succeed.
- What gets captured: lookaheads contribute nothing to the matched text. If you need the full line returned, keep a consuming part such as .* after them.
Will the pattern still work after you copy it somewhere else?
A regex is not a universal format. Moving it between tools is the most common way an AND pattern breaks. Lookaround is documented as supported in Perl, PCRE, Python's re module, JavaScript, Java, .NET and Ruby. It is documented as unsupported in Go's regexp package and other RE2-based engines, in Rust's regex crate, and in POSIX basic and extended regular expressions, which are used by plain grep, grep -E, sed and standard awk. In those engines, a lookahead is either rejected as a syntax error or not interpreted as a lookahead. Neither result gives you AND. GNU grep's -P option switches to PCRE-style matching, but only if your build includes it. Check before relying on it in scripts that run on other machines.
# PCRE-capable grep: both words, any order
grep -P '^(?=.*\bred\b)(?=.*\bblue\b)' notes.txt
# Portable: one simple filter per condition
grep 'red' notes.txt | grep 'blue'
# POSIX extended regex, ordered alternatives (grows quickly with more terms)
grep -E 'red.*blue|blue.*red' notes.txt
Escaping layers also change a pattern in transit. In a shell, wrap patterns in single quotes. In interactive bash with history expansion enabled, the ! in a negative lookahead can be expanded inside double quotes. In Java and C# ordinary string literals, in JSON and in YAML double-quoted strings, every backslash must be doubled, so \b becomes \b. Python raw strings and C# verbatim strings avoid most of this. When a pattern stops working after being pasted into a new file or config, compare the escaping before you suspect the logic.
Readability for the next person who edits the pattern matters too. Python, PCRE, Perl, Java, .NET and Ruby offer a verbose or extended mode that ignores unescaped whitespace and allows comments. This lets each condition sit on its own line.
import re
both_colors = re.compile(r"""
^
(?=.*\bred\b) # must contain the word "red"
(?=.*\bblue\b) # must contain the word "blue"
""", re.VERBOSE | re.IGNORECASE)
print(bool(both_colors.search("Blue sky over a red barn"))) # expected: True
print(bool(both_colors.search("A red barn"))) # expected: False
Online regex testers usually let you pick a flavor. A pattern that passes in one flavor is not evidence that it works in another, so select the engine your code will actually use. A tester's appearance or wording says nothing reliable about what happens to the text you paste in. Avoid pasting logs, credentials or personal data unless you have verified how that tool handles input.
When separate checks are the better choice
If you control the code, testing each condition separately and combining the results with the language's own AND is often the plainest solution. Each check stays simple, works in any engine and can be read without knowing lookaround syntax. For validation, such as password rules requiring a digit, an uppercase letter and a minimum length, separate checks have another practical advantage. You can tell the user exactly which rule failed, instead of returning a single pass or fail from one combined pattern.
import re
terms = ["red", "blue", "green"]
line = "Green paint, blue tape, red brush"
has_all = all(
re.search(rf"\b{re.escape(t)}\b", line, re.IGNORECASE)
for t in terms
)
Performance considerations
Each lookahead that begins with .* scans forward from the anchor. An anchored pattern therefore does work roughly proportional to the number of conditions times the length of the line. An unanchored pattern that fails can repeat that scan from many starting positions, which matters on long lines or large files. No measurements were supplied for this review. If speed matters, time the lookahead version against separate checks on your own data and engine rather than assuming either is faster.
What this review could not verify
No tool-specific evidence, benchmarks or test results were provided. The flavor support described here reflects the engines' documented general behavior, not tests run for this article. The expected outputs in the examples follow from documented lookahead semantics, not from recorded runs. Feature availability can depend on version and build. The JavaScript v flag requires a recent runtime, and grep -P depends on how grep was compiled. Confirm both against the documentation for the exact engine and version you deploy.