0

I have a problem with my regex. I didn't test this before. I have the following regex:

^(?:(?:[a-z])+(.|_)?(?!\.))*\w@(?:(?:[a-z])+(-|.)?(?!\.))*\w\.\w{2,}$

Now, my email validation halfly works. Here are some tests (according to regex101):

test -- invalid
test@ -- invalid
test@test -- invalid
test@test. -- invalid
test@test.de -- valid
test@test.de. -- invalid
test@test@test.com -- valid
test...test@test.com -- invalid

So, more than one @ can be used which is invalid for an email.

I kind of cannot see what I'm doing wrong.

NOTE:

I know there's a stackoverflow question that has a method on how to validate email with regex, HOWEVER: I'd like to know what I did wrong so I can learn from it.

Joshua Bakker
  • 2,288
  • 3
  • 30
  • 63

1 Answers1

1

I found out the problem myself. The following regex does work:

^(?:(?:\w)+(\.|_)?(?!\.))*\w@(?:(?:[a-z])+(-|\.)?(?!\.))*[a-z]\.[a-z]{2,}$

I changed (.|_) into (\.|_) and (-|.) into (-|\.) to use . literally as a period and not as an 'all character "wildcard"'. I changed \w\.\w{2,} in [a-z]\.[a-z]{2,} to disallow _ in the last part.

Joshua Bakker
  • 2,288
  • 3
  • 30
  • 63