1

I was working around some regex pattern

I have a variable,

var url = "last_name=Ahuja&something@test.com";

The url contains emailId. I have a regex pattern to check if the variable contains emailId.

var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

My requirement is: I want exact negate(opposite) of the above pattern. Like, My condition should be false if the url contains email pattern. I mean the regex pattern should be in that way.

Can somebody please help me on this.

  • 1
    https://hackernoon.com/the-100-correct-way-to-validate-email-addresses-7c4818f24643 – Hackerman Jan 08 '18 at 17:32
  • 2
    Possible duplicate of [Regular expression to match a line that doesn't contain a word?](https://stackoverflow.com/questions/406230/regular-expression-to-match-a-line-that-doesnt-contain-a-word) – Pac0 Jan 08 '18 at 17:35
  • 1
    The two answers (currently) on this question will both claim that _**my**_ actual, perfectly valid email address is _not valid_. Read Hackerman's link and heed its warnings. People try to use a regex that is _far too simple_ when matching email, and there's no point doing it anyway since you should send a confirmation email to the address entered. – Stephen P Jan 08 '18 at 21:27

2 Answers2

0

Instead of negating your regex, you can test whether it matches.

var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var url = "last_name=Ahuja&something@test.com";

if(-1 === url.search(filter))
{
    alert("Didn't find it");
}
else
{
    alert("Found it");
}
Jonathan
  • 339
  • 1
  • 8
0

Using a negative lookahead you can check if the string does not have an email at the beginning, which mimics the behavior you want since your regex had start and end anchors.

^(?!([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+).*$

But if you wanted to make sure there was no valid email anywhere in the line, you could modify this a little.

^((?!([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+).)*$

See an explanation here

But you should just do this in code like Jonathan suggests.

Hasan
  • 190
  • 4
  • 12