Search code examples
javascriptregexstringlookbehindnegative-lookbehind

Regex to find whether given text not contain only email string


I want to write a regex (java script) to match if the given text not contain only an email string.

for ex:

  • abc -> should match
  • abs@gmail.com sss -> should match
  • abs@gmail.comsss -> should match
  • aaa abs@gmail.com -> should match
  • abc@gmail.com -> should not match

I wrote a regex using (?<!…) Negative lookbehind, to check whether given text does contain only email string or not as below. But I cant use + inside lookbehind expression and it gives A quantifier inside a lookbehind makes it non-fixed width error.

regex:

^.+(?<!([a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.com))$

explanation:

  • ([a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.com) - regex to check email address.
  • ^.+(?<!([a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.com))$ - regex to check look behind of all non empty texts (.+)

Please give me an idea to resolve this issue...

Thanks


Solution

  • One approach is to enclose the pattern of an email address in a negative lookahead assertion with anchors:

    ^(?![a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.com$)
    

    Demo: https://regex101.com/r/gutJB8/1

    Note that your example of aaaabs@gmail.com in the question should not match even though you claim that it should.