Regular Expression - Assertions
An assertion (Assertion) is a metacharacter in regular expressions used to specify a match position. They do not match any actual character, but rather match the position between characters.
Suppose we want to find all numbers that follow a price in a long text, rather than finding all numbers. A normal regex might match all numbers, but with assertions you can specify precisely:I only match numbers that immediately follow a price.
This article will guide you through the four core assertions in regular expressions: positive lookahead, negative lookahead, positive lookbehind, and negative lookbehind.
Characteristics of assertions
- Zero-width: does not occupy the position of matched characters
- Condition check: only checks whether a specific condition is met
- Does not affect the match result: only serves as a constraint on the match
Example
// Example: match foo followed by bar
const
regex
=
/foo(?=bar)/
;
console.
log
(
regex.
test
(
"foobar"
)
)
;
// true
console.
log
(
regex.
test
(
"food"
)
)
;
// false
Types of assertions
Assertions in regular expressions are mainly divided into two categories and four types:
| Assertion type | Regex syntax | Alias | Check direction | Expected condition | Plain explanation |
|---|---|---|---|---|---|
| Positive lookahead | (?=pattern) |
Positive lookahead | Rightward (forward) | Exists pattern |
The position I want to find, itsright side mustbe ... |
| Negative lookahead | (?!pattern) |
Negative lookahead | Rightward (forward) | Not found pattern |
The position I want to find, itsright side must notbe ... |
| Positive lookbehind | (?<=pattern) |
Positive lookbehind | Leftward (backward) | Exists pattern |
The position I want to find, itsleft side mustbe ... |
| Negative lookbehind | (? |
Negative lookbehind | to the left (backward) | Not found pattern |
the position I want to find, itsthe left side must notis... |
Positive lookahead assertion (?=...)
Positive lookahead assertion Used to match such a position: after which (to the right), the specified pattern must appear immediately following ....
Syntax and parameters
- Syntax:
(?=pattern) - Purpose: check whether the right side of the current position matches
pattern. If it matches, the assertion succeeds, and the engine returns to the current position to continue subsequent matching. - Key characteristics:Zero-width, that is, it only checks, it does not "consume" any characters.
patternthe content within will not become part of the final match result.
Code example 1: extract price numbers
Suppose we have a string of text and need to extract all the amount numbers after "price:".
Example: JavaScript
const
text
=
"Product A price: 299 yuan, Product B price: 599 yuan, shipping: 20 yuan."
;
// positive lookahead assertion
// match one or more digits, but require the right side to be immediately followed by "yuan"
// The "yuan" itself is not part of the match result
const
pattern
=
/\d+(?=yuan)/g
;
const
matches
=
text.
match
(
pattern
)
;
console.
log
(
"Matched price numbers:"
,
matches
)
;
// output: ['299', '599', '20']
Example: Python
import
re
text
=
"Product A price: 299 yuan, Product B price: 599 yuan, shipping: 20 yuan."
Use a positive lookahead assertion
Match one or more digits (\d+), but require that the right side of this digit be immediately followed by "yuan"
Note: the "yuan" itself will not be matched into the result
pattern
=
r
'\d+(?=yuan)'
matches
=
re
.
findall
(
pattern
,
text
)
(
"Matched price numbers:"
,
matches
)
Output: matched price numbers: ['299', '599', '20']
Code Analysis:
\d+is the main expression, matching one or more digits.(?=元)is an assertion; it checks\d+of the matched digit stringright sidewhether it is immediately followed by the character "yuan".- the engine first finds
299, then looks right, finds it is "yuan", assertion succeeds, so299is recorded. - continue to find
599, the right side is "yuan", success, recorded. - found
20, the right side is "yuan", success, recorded. Finally, we only got the numeric part.
Code example 2: validate a complex password
Requires the password to contain at least one uppercase letter, one lowercase letter, and one digit.
Example: JavaScript
function
validatePassword
(
password
)
{
// multiple positive lookahead assertions
const
pattern
=
/^(?=.[A-Z])(?=.[a-z])(?=.*\d).{8,}$/
;
// ^ start of string
// (?=.*[A-Z]) the right side must contain at least one uppercase letter
// (?=.*[a-z]) the right side must contain at least one lowercase letter
// (?=.*\d) the right side must contain at least one digit
// .{8,} total length at least 8
// $ end of string
return
pattern.
test
(
password
)
;
}
// test data
const
passwords
=
[
"Weak"
,
"strong123"
,
"STRONG123"
,
"Strong123"
]
;
passwords.
forEach
(
pwd
=>
{
console.
log
(
`password `
'${pwd}'
is valid: $
{
validatePassword
(
pwd
)
}
`
)
;
}
)
;
// output:
// Is password 'Weak' valid: false
// Is password 'strong123' valid: false
// Is password 'STRONG123' valid: false
// Is password 'Strong123' valid: true
Example: Pyhton
import
re
def
validate_password
(
password
)
:
Use multiple positive lookahead assertions to check conditions separately
pattern
=
r
'^(?=.[A-Z])(?=.[a-z])(?=.*\d).{8,}$'
^ represents the start of the string
(?=.[A-Z]) assertion: from the current position (the beginning), looking right, must be able to find within any character () find an uppercase letter afterward
(?=.*[a-z]) assertion: similarly looking right from the start, must be able to find a lowercase letter
(?=.*\d) assertion: looking right from the start, must be able to find a digit
.{8,} main expression: matches any character at least 8 times (total length requirement)
$ represents the end of the string
if
re
.
match
(
pattern
,
password
)
:
return
True
else
:
return
False
Test Data
passwords
=
[
"Weak"
,
"strong123"
,
"STRONG123"
,
"Strong123"
]
for
pwd
in
passwords:
(
f
"Is password '{pwd}' valid: {validate_password(pwd)}"
)
Output:
Is password 'Weak' valid: False # length insufficient, and missing digit
Is password 'strong123' valid: False # missing uppercase letter
Is password 'STRONG123' valid: False # missing lowercase letter
Is password 'Strong123' valid: True # meets all conditions
Negative lookahead assertion (?!...)
Negative lookahead assertion Opposite of a positive lookahead assertion. It matches a position, after which (to the right), cannotthe specified pattern appears immediately following ....
Syntax and parameters
- Syntax:
(?!pattern) - Purpose: check whether the right side of the current positionNo match
pattern. If it does not match, the assertion succeeds. - Key characteristics: also zero-width.
Code example: find words not ending in ing
In a sentence, find all that do not end with ing words ending with.
Example: JavaScript
// Example 1: negative lookahead assertion
const
text1
=
"playing swimming run walk jumping sing"
;
const
pattern1
=
/\b\w+(?
;
console.
log
(
text1.
match
(
pattern1
)
)
;
// ['run', 'walk', 'sing']
// Example 2: match words not ending in q (correct semantic version)
const
text2
=
"I like faq apple Iraq you banana q"
;
const
pattern2
=
/\b\w*[^q\W]\b/g
;
// meaning:
// [^q\W] the last character of the word is not q
// better matches the real need of "ending is not q" than (?!q)
console.
log
(
text2.
match
(
pattern2
)
)
;
// ['I', 'like', 'apple', 'you', 'banana']
// Example 3: match filenames not ending in .js
const
files
=
"index.js app.ts config.json main.js readme.md"
;
const
pattern3
=
/\b\w+.(?!js\b)\w+\b/g
;
// meaning: .(?!js\b) after the dot must not be js
console.
log
(
files.
match
(
pattern3
)
)
;
// ['app.ts', 'config.json', 'readme.md']
Positive lookbehind assertion (?<=...)
Positive lookbehind assertion Used to match a position, before which (to the left), the specified pattern must appear immediately adjacent ....
Note: not all programming languages' regex engines support lookbehind assertions; JavaScript only fully supported them after ES2018, and Python's re Module support.
Syntax and parameters
- Syntax:
(?<=pattern) - Purpose: check whether the left side of the current position matches
pattern. If it matches, the assertion succeeds. - Key characteristics: zero-width.
patternmust be of fixed length (cannot be*or+and other variable-length quantifiers, in some implementations).
Code example: extract the amount after a currency symbol
Extract the digits after a dollar or pound sign, but do not include the sign itself.
Example: JavaScript
// Example 1: match the amount after $ or £ (classic, semantically correct)
const
text1
=
"Price: $199, £89, ¥1200"
;
const
pattern1
=
/(?<=$|£)\d+/g
;
// meaning:
// (?<=$|£) the left side must be $ or £
// \d+ matches the digit itself
console.
log
(
text1.
match
(
pattern1
)
)
;
// ['199', '89']
// Example 2: match the digits after a colon
const
text2
=
"port:8080 pid:1234 uid:1000"
;
const
pattern2
=
/(?<=:)\d+/g
;
// the left side must be :
console.
log
(
text2.
match
(
pattern2
)
)
;
// ['8080', '1234', '1000']
// Example 3: match the minor version in a version number (after the major version)
const
text3
=
"v1.2 v2.15 v10.3"
;
const
pattern3
=
/(?<=v\d+.)\d+/g
;
// the left side must be v + digit + dot
console.
log
(
text3.
match
(
pattern3
)
)
;
// ['2', '15', '3']
// Example 4: match the username after @ (excluding @)
const
text4
=
"hello @alice and @bob_smith"
;
const
pattern4
=
/(?<=@)[a-zA-Z_]\w*/g
;
console.
log
(
text4.
match
(
pattern4
)
)
;
// ['alice', 'bob_smith']
// Example 5: match the chapter number in the "Chapter X" pattern
const
text5
=
"Chapter 1, Chapter 12, Chapter 3"
;
const
pattern5
=
/(?<=Chapter)\d+(?=Chapter)/g
;
// constraining both left and right is clearer
console.
log
(
text5.
match
(
pattern5
)
)
;
// ['1', '12', '3']
Negative lookbehind assertion (?
Negative lookbehind assertion is the opposite of a positive lookbehind assertion. It matches a position, before which (to the left),cannotthe specified pattern appears immediately adjacent ....
Syntax and parameters
- Syntax:
(? - Purpose: check whether the left side of the current positionNo match
pattern. - Key characteristics: zero-width, usually requires
patternis of fixed length.
Code example: find non-negative integers
In a piece of text, match all integers that are not negative numbers (i.e., there is no minus sign on the left - the digits).
Example: JavaScript
const
text
=
"Today's temperature is -5 degrees, rising to 3 degrees tomorrow, the day after tomorrow -1 degrees, and the indoor temperature stays at 22 degrees."
;
// negative lookbehind assertion (lookbehind)
// match digits, but require the left side not to be a minus sign -
const
pattern
=
/(?
;
const
matches
=
text.
match
(
pattern
)
;
console.
log
(
"Non-negative integer:"
,
matches
)
;
// output: ['3', '22']
// -5. -1 has '-' on the left, assertion fails, no match
Comprehensive application and flowchart
To understand the workflow of the four types of assertions more intuitively, we can use the following flowchart to represent a complex matching process involving multiple assertions:

Flowchart explanation: this diagram shows how the regular expression engine handles assertions during matching. The core is that, An assertion is an independent check node. The engine attempts to match in the main expression atcurrent position, depending on the assertion type, it checks the context to the left or right. Only when all assertion conditions are satisfied can the match continue downward and "consume" characters; otherwise, the engine backtracks to try other possibilities or declares the match failed.
Positive lookahead assertion
Negative lookahead assertion
Positive lookbehind assertion
Negative lookbehind assertion
Comprehensive practice
Interactive testing
Positive lookahead assertion
(?=pattern)
Negative lookahead assertion
(?!pattern)
Positive lookbehind assertion
(?<=pattern)
Negative lookbehind assertion
(?
Comprehensive practice example
Interactive test area