const regex = /(err\s*?\d{1})|[^\d]\s+(\d{3})(?:$|\s+(?!\d))/gmi;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(err\\s*?\\d{1})|[^\\d]\\s+(\\d{3})(?:$|\\s+(?!\\d))', 'gmi')
const str = `The below items should match:
-----------------------------
123
456 123
123 324 324
Match the number in this sentence 123 as well
999
The below items should NOT match:
---------------------------------
1234
12345
123456
1234567
£123
\$456
Err404
ERR404
err404
Err 404
ERR 404
err 404
there is err 404 on page
this err 1232222222222 as well
a string 12323 like this
asd
4444333322221111
4444 3333 2222 1111
Err123
02012341234
920 1234 1234`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions