December 2023
Intermediate to advanced
242 pages
5h 28m
English
| Recipe 50 | Testing a Pattern with the Negative Lookbehind |
Suppose you’re searching hospital records for a patient named Smith, but most of the data you get from search results is about Dr. Smith. You need a regex that matches “Smith” but excludes “Dr. Smith.”
Use a negative lookbehind assertion denoted by (?<! ... ):
| | const re = /(?<!Dr\.\s)Smith/; |
| | |
| | console.log(re.test("Dr. Smith")); // → false |
| | console.log(re.test("Mr. Smith")); // → true |
| | console.log(re.test("John Smith")); // → true |
Your regex now finds all records containing “Smith” except for “Dr. Smith.”
The negative version of lookbehind asserts that the pattern within the lookbehind does ...
Read now
Unlock full access