1

I am looking for a valid regexp for my email validation requirement. I tried several times, but it buggy.

here is my try: .*@[^\W_]+(?:[\w-]*[^\W_])

need to fit with:

xxx@_domain.com => invalid @ starts with _
xxx@domain_.com => invalid domain ends with _ 
xxx@-domain.com => invalid @ starts with - ( hypen)
xxx@domain-.com => invlaid domain ends with - (hypen)
-xxx@domain.in => invalid domain start with - (hypen)
xxx@111.com => invalid domain only contains numbers
xxx@1and1.com => valid domain contains both number and chars
xxx@us.com => valid
xxx@my-india.com => valid
xxx@me2.com => valid
xxx@tv.com =>
xxx@abc_efg.com =>  valid _ inside the chars
_muth@tamil.com => valid _ start with 

any one help me?

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

1

If this email value comes from a HTML input, i think the best way is to just set the type property to email and let the browser do the hard work, but if this is not the case, you can check Regexr, there's some community regex already created and it's quite a useful tool

Breno Prata
  • 712
  • 5
  • 10
1

For your specific requirements you might use

^\w+(?:[_-][^\W_]+)*@(?![\d._-]+\.[^\W_]+$)[^\W_]+(?:[_-][^\W_]+)*\.[^\W_]{2,3}$

Explanation

  • ^ Start of string
  • \w+ Match 1+ word chars
  • (?:[_-][^\W_]+)* Repeat 0+ times matching - or - and 1+ word chars except _
  • @ Match literally
  • (?! Negative lookahead, assert what is on the right is not
    • [\d._-]+\.[^\W_]+$ Assert only digits or any of ._- until the end of the string
  • ) Close lookahead
  • [^\W_]+ Match 1+ times a word char except _
  • (?:[_-][^\W_]+)* Repeat 0+ times matching - or - and 1+ word chars except _
  • \.[^\W_]{2,3} Match . and 2-3 times a word char except _
  • $ End of string

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70