Combining lookarounds
Stack lookaheads for must-contain-all rules, insert thousands separators, exclude a shape, and see when separate checks in code beat one clever pattern.
Combining lookarounds
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Lookarounds do not consume, so you can stack several at one position. Each one tests the same text from the same starting point, and all must pass: ^(?=.*\d)(?=.*[a-z]) means contains a digit AND a lowercase letter.
- A password-style rule is a stack of positive lookaheads at ^ followed by a normal pattern that does the length check and consumes the string. The order of the lookaheads does not change the result.
- Thousands separators are a replace of a position, not of text: /\B(?=(?:\d{3})+(?!\d))/g with ',' turns 1234567 into 1,234,567. It misfires on long decimal fractions.
- A negative lookahead at the start excludes a shape: ^(?!.*\.min\.js$).*\.js$ matches .js files except .min.js ones.
- The cost is readability. Four separate tests in code give the same answer and can tell the user which rule failed, which one regex cannot.
Several conditions, one starting point
A signup form says: at least 8 characters, with a lowercase letter, an uppercase letter, a digit and a symbol. As a regex, “contains a digit anywhere” is easy. “Contains a digit and a lowercase letter” is awkward, because a normal pattern reads left to right and consumes as it goes. To demand two things anywhere in a string, in any order, you would need to write every ordering as an alternation, and that grows quickly.
Lookarounds don’t consume. So you can stand at the start of the string and ask several questions in a row, each starting from the same spot. Every question has to come back “yes”. Picture a checkpoint with four inspectors who each look at your whole bag, one after another, and nobody removes anything from it. Only after all four have signed off do you walk through to the “real” matching.
The password pattern
const pw = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$/;
Read it as: at the start, there is (somewhere ahead) a lowercase letter; and (somewhere ahead) an uppercase letter; and a digit; and a character that’s neither a word character nor whitespace; and then the string is at least 8 characters, all the way to the end. I ran it:
Passw0rd! true
password1! false (no uppercase)
PASSWORD1! false (no lowercase)
Password!! false (no digit)
Passw0rd false (no symbol)
Pa1! false (too short)
Pass w0rd! true (a space is allowed; nothing said otherwise)
Each .* inside a lookahead scans forward to wherever the thing might be. Reordering the lookaheads changed nothing. I tried (?=.*\d)(?=.*[a-z]) against (?=.*[a-z])(?=.*\d) on four inputs and got identical results both ways. Python 3.9 gave the same answers for the same pattern, and pcre2grep accepted it when I fed it two lines.
One catch: . doesn’t match a newline. For 'Passw0rd\n!', the pattern returned false, and replacing . with [\s\S] made it true. In Python the equivalent is the re.S flag; on the same input it went from False to True. If the field can be multi-line, handle it.
Thousands separators
The same idea works in a replacement. You don’t want to match digits. You want to match the empty places where a comma goes: places that are not at the start of a number, and from which the rest of the digits form complete groups of three.
const comma = /\B(?=(?:\d{3})+(?!\d))/g;
'1234'.replace(comma, ',') // '1,234'
'1234567'.replace(comma, ',') // '1,234,567'
'12345678901'.replace(comma, ',') // '12,345,678,901'
'123'.replace(comma, ',') // '123'
\B means “not at a word edge”, so no comma lands at the front. (?=(?:\d{3})+(?!\d)) says there is at least one triple of digits ahead, and after the last triple no more digits follow. The pattern never consumed a character; it only chose positions. This is a good example because the match is always empty.
It has a flaw I found by trying a long fraction:
'0.1234567'.replace(comma, ',') // '0.1,234,567'
The fractional digits get commas too, because from their point of view they are also a run of digits. For real code the fix could use the lookbehind from last lesson: add (?<!\.\d*) to refuse positions that have a decimal point somewhere before them. On '1234567.1234567' it returned 1,234,567.1234567. That only works where JavaScript allows variable-length lookbehind. In practice, the platform formatter is better: new Intl.NumberFormat('en-US').format(1234567.891) printed 1,234,567.891. I didn’t test locales that group differently.
Excluding a shape
A negative lookahead at the start says “whatever else this pattern is, it must not look like this”:
const files = ['app.js','app.min.js','lib/util.js','style.css','vendor.min.js'];
files.filter(f => /^(?!.*\.min\.js$).*\.js$/.test(f))
// [ 'app.js', 'lib/util.js' ]
The same filter in plain code, /\.js$/.test(f) && !/\.min\.js$/.test(f), gave the same list. pcre2grep ran the lookahead version correctly on a two-line test.
What it costs
The password regex is 50 characters of punctuation that few people can read at a glance. When it fails, all it says is false. Here is the same rule as five small tests:
const rules = [/[a-z]/, /[A-Z]/, /\d/, /[^\w\s]/, /^.{8,}$/s];
rules.every(r => r.test('Passw0rd!')) // true
For Passw0rd and password1!, mapping over the rules reported that the symbol rule failed for the first and the uppercase rule failed for the second. So the user can be told “add a symbol”. The single regex can’t say that. Use a stacked-lookahead pattern when you must express the rule as one regex, such as in an HTML pattern attribute, a config file or a router. In code you control, a list of small checks is easier to change, test and explain.
About the video
The embedded video is Useful Programmer’s “Regular Expressions - Positive and Negative Lookahead - Free Code Camp”, published 16 December 2019 and 6 minutes 32 seconds long. Its chapters are Intro, Examples and Practical Examples. The description says it uses positive and negative lookaheads with JavaScript methods, as part of the freeCodeCamp curriculum, I couldn’t read a transcript, so I can’t say what its practical examples are. The password, thousands-separator and exclusion examples above are my own runs, not the video’s. English per its title and description. A second option under “deeper” is Leela Web Dev’s six-minute password-strength video, which I judged a narrower fit.
What I did not run
Locale-specific number grouping, an HTML pattern attribute in a browser, and GNU grep -P.
Next
Lookarounds are one kind of extra control over how a pattern behaves. The other kind is flags that change the rules for the whole pattern, starting with ignore case, global and multiline.
Check yourself
In /^(?=.*\d)(?=.*[a-z]).{6,}$/, why do the two lookaheads not interfere with each other?
Neither consumes characters, so each starts fresh from the same position at the start of the string. Both scan the whole input for their own requirement, and then .{6,} does the real matching from the start.
Why does the password pattern use .* inside each lookahead, and what breaks if the input has a newline?
.* lets the condition look anywhere ahead on the line. But . does not match a newline by default, so for Passw0rd, a newline and ! the lookaheads and .{8,} cannot see across the break and the test failed. Use the s flag or [\s\S].
How does /\B(?=(?:\d{3})+(?!\d))/g add commas?
It matches an empty position that is not at a word edge and that has a whole number of three-digit groups from here to the end of the digits. Each such position gets a comma, which is exactly where thousands separators belong.
When would you replace a stack of lookaheads with separate checks in code?
When you need to tell the user which rule failed, when rules change often, or when a reviewer must be able to read the rule list. The lookahead version answers only yes or no for the whole stack.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.