Lookahead and Lookbehind
Use positive and negative lookahead and lookbehind to match text only in the right context, enforce password rules and format numbers.
Welcome back!
Step 1 of 14Learn
Peeking without stepping
You need every price in a text, but only the number, not the currency: in "Total: USD 250 and EUR 99," you want 250 only when it follows "USD." Or you want to find the word "Java" but not when it's part of "JavaScript." Both tasks depend on context: what comes before or after a match, without including that context in the match itself.
Lookarounds do exactly that. They are zero-width assertions, like ^ and \b: they check a condition at the current position and consume no characters.
| Syntax | Name | Succeeds if... |
|---|---|---|
(?=...) | positive lookahead | what follows matches |
(?!...) | negative lookahead | what follows does not match |
(?<=...) | positive lookbehind | what precedes matches |
(?<!...) | negative lookbehind | what precedes does not match |
Examples:
Java(?!Script)matches "Java" in "Java and JavaScript" only at the first word.(?<=USD )\d+matches "250" in "USD 250" but not "99" in "EUR 99."\d+(?= dollars)matches "40" in "40 dollars" but not in "40 euros."
Because lookarounds don't consume text, the match contains only the part you want, which makes extraction and replacement simpler.
Step 2 of 14Compare
The four lookarounds
| Aspect | Looks | Must be there? | Example |
|---|---|---|---|
| (?=...) | Ahead | Yes | \d+(?=USD): 30 in 30USD |
| (?!...) | Ahead | No | Java(?!Script) |
| (?<=...) | Behind | Yes | (?<=USD)\d+: 60 in USD60 |
| (?<!...) | Behind | No | (?<!\$)\d+ |
Step 3 of 14Practice · Match the pairs
Match each pattern to what it finds in the text "price 30USD, 45EUR, USD60".
Tap an answer, then tap the place where it belongs (or drag it there).
\d+(?=USD)\d+(?=EUR)(?<=USD)\d+\d+(?!\d|USD)
Step 4 of 14Learn
Several rules at once: password checks
Lookaheads shine when a string must satisfy several independent conditions. A sign-up form requires a password that:
- is at least 8 characters long,
- contains at least one digit,
- contains at least one uppercase letter.
Each condition is easy alone, but they can appear in any order. Stacked lookaheads at the start of the string check them all:
^(?=.*\d)(?=.*[A-Z]).{8,}$Read it from the left. At position 0, (?=.*\d) peeks ahead: is there a digit somewhere? It consumes nothing, so the engine is still at position 0. Then (?=.*[A-Z]) peeks again: is there an uppercase letter somewhere? Finally .{8,}$ actually consumes the whole string and checks the length.
Adding a rule is just adding a lookahead: (?=.*[^A-Za-z0-9]) requires a symbol. A negative lookahead can forbid something: (?!.*\s) rejects passwords containing whitespace.
A caution on design: long rule lists frustrate users and don't add as much security as length does. Current guidance from security agencies such as NIST favors longer passwords and checks against lists of commonly used passwords over strict composition rules. The regex technique, though, is useful for any multi-condition validation.
Step 5 of 14Practice · Diagram
^(?=.\d)(?=.[A-Z]).{8,}$ step by step
Which part actually consumes characters?
Tap the shape that answers the question, then press Check.
- ^ at position 0
- (?=.*\d): any digit ahead?
Peeks, consumes nothing. Still at position 0.
- (?=.*[A-Z]): any capital?
Peeks again from position 0.
- .{8,}$ consumes it all
Checks the length and that nothing is left over.
Step 6 of 14Practice · Sort into groups
Does each password pass ^(?=.*\d)(?=.*[A-Z]).{8,}$?
Tap an item, then tap its group (or drag it there).
Step 7 of 14Learn
Lookbehind and its limits
Lookbehind checks what comes before the current position. It's handy for extracting values that follow a label:
(?<=\$)\d+(\.\d{2})?matches the amount after a dollar sign, without the sign.(?<=@)\w+matches the username after an @ in a mention.(?<!-)\b\d+\bmatches numbers not preceded by a minus sign.
Lookbehind support varies more than any other common feature:
- JavaScript supports lookbehind of any length (it arrived in ES2018 and is available in all current browsers).
- Python, PCRE and Java require lookbehind to have a fixed length, or at least a bounded maximum length in Java.
(?<=USD|EUR)works in Python because both alternatives are three characters, but(?<=\$\s*)fails because\s*has no fixed length. - POSIX tools like basic grep and sed don't support lookarounds at all.
When lookbehind isn't available or allowed, a capturing group usually does the job: match \$(\d+) and read group 1. Lookarounds make patterns shorter, but groups are more portable.
Step 8 of 14Note
Step 9 of 14Diagram
Thousands separators with lookarounds
Tap a shape with to see more.
- 1234567
- Find positions
\B(?=(\d{3})+(?!\d)): inside the number, followed by groups of exactly three digits to the end.
- After 1 and after 4
1|234|567
- 1,234,567
Replace each zero-width position with a comma.
Step 10 of 14Practice · Code challenge
Write isStrongPassword(pw) that returns true only if the password is at least 10 characters long, contains at least one digit, at least one lowercase letter and at least one uppercase letter, and contains no whitespace. Use a single regex with lookaheads.
isStrongPassword("CorrectHorse9")isStrongPassword("correcthorse9")isStrongPassword("CORRECTHORSE9")isStrongPassword("CorrectHorse")isStrongPassword("Short9a")isStrongPassword("Correct Horse9")
Step 11 of 14Practice · Spot the mistake
Tap the two patterns that would be rejected by Python's re module because their lookbehind does not have a fixed length.
Step 12 of 14Note
Step 13 of 14Note
Step 14 of 14Practice · Choose one
Which pattern matches "Java" only when it is NOT followed by "Script"?
Lesson complete!