How to negatively match a specific value with RegEx -


i want negatively match specific value (let's 42) using (javascript) regex.

i know how positively match value:

/^42$/.test(42); // true /^42$/.test(43); // false /^42$/.test(422); // false 

i looking inverse of this:

/somemagic/.test(42); // false /somemagic/.test(43); // true /somemagic/.test(422); // true 

the solutions google-fu turned didn't work use case because care matching entire value being tested, not piece of it.

i have searched endlessly this... appreciated!

thanks!

you need anchored negative lookahead:

document.write(/^(?!42$)\d+$/.test(42) + "<br/>");  document.write(/^(?!42$)\d+$/.test(43) + "<br/>");  document.write(/^(?!42$)\d+$/.test(422));

the (?!42$) lookahead checks @ beginning of string if string 42 (since $ asserts end of string). thus, 42 not match \d+ pattern.

this technique add exceptions more generic patterns, shorthand or character classes, , patterns optional groups.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -