Negative Lookbehind Assertions


You can define a subexpression to ascertain that a pattern does not appear before the current position in the input string. They are called negative lookbehind asserstions. They are zero-width assertions, meaning they do not consume any characters.

To match the file ‘instructions.pdf‘ only if it is NOT directly under the 'admin\' folder

let wordPttn = /(?<!admin\\)instructions\.pdf/;
let targetString = "E:\\Users\\admin\\instructions.pdf";
let result = targetString.match(wordPttn);
console.log((result !== null ?
`Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));
targetString = "E:\\abc\\def\\sysaminprod\\ghi\\ijk\\instructions.pdf";
result = targetString.match(wordPttn);
console.log((result !== null ?
`Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));

Output:

Pattern /(?<!admin\\)instructions\.pdf/ NOT FOUND in 'E:\Users\admin\instructions.pdf'
Pattern /(?<!admin\\)instructions\.pdf/ FOUND in 'E:\abc\def\sysaminprod\ghi\ijk\instructions.pdf'. Matched string is 'instructions.pdf'

To match the file ‘instructions.pdf‘ only if the folder ‘admin\‘ DOES NOT occur some where in the file path. Assume the folder names contain only the characters [a-z], [A-Z], [0-9] and - (hyphen)

let wordPttn = /(?<!([\w-]+\\)*admin\\([\w-]+\\)*)instructions\.pdf/;
let targetString = "E:\\abc\\def\\admin\\ghi\\ijk\\instructions.pdf";
let result = targetString.match(wordPttn);
console.log((result !== null ? `
Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));
targetString = "E:\\abc\\def\\sysadminprod\\ghi\\ijk\\instructions.pdf";
result = targetString.match(wordPttn);
console.log((result !== null ?
`Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'`
: `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));

Output:

Pattern /(?<!([\w-]+\\)*admin\\([\w-]+\\)*)instructions\.pdf/ NOT FOUND in 'E:\abc\def\admin\ghi\ijk\instructions.pdf'
Pattern /(?<!([\w-]+\\)*admin\\([\w-]+\\)*)instructions\.pdf/ FOUND in 'E:\abc\def\sysadminprod\ghi\ijk\instructions.pdf'. Matched string is 'instructions.pdf'