const regex = /(?<![{\d#])\d+(?![\d}]|st|nd|rd|th)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?<![{\\d#])\\d+(?![\\d}]|st|nd|rd|th)', 'gm')
const str = `123abd //should match 123
abc345 //should match 234
ab2123cd // should match 2123
{2}: Should NOT Match. //My regex Works
{34: Should NOT Match. //My regex matches 4 in {34
45}: Should NOT Match. //My regex matches 4 in {45
{123}: Should NOT Match. //My regex matches 2 in {123}
1st should NOT match
3th should NOT match, since it's wrong anyway
1nd should NOT match, since it's wrong anyway
14th //should NOT Match
14 th should Match
like 1st, 2nd, etc or #1, #2, etc`;
// 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