Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why /^[a-zA-Z0-9]+@[a-zA-Z0-9]\.(com)|(edu)|(org)$/i does not work as expected

Tags:

regex

I have this regex for email validation (assume only [email protected], [email protected], [email protected] are valid)

/^[a-zA-Z0-9]+@[a-zA-Z0-9]\.(com)|(edu)|(org)$/i

But @abc.edu and [email protected] are both valid as to the regex above. Can anyone explain why that is?

My approach:

  1. there should be at least one character or number before @

  2. then there comes @

  3. there should be at least one character or number after @ and before .
  4. the string should end with either edu, com, or org.
like image 418
Dustin Sun Avatar asked Jan 07 '23 06:01

Dustin Sun


2 Answers

Try this

/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.(com|edu|org)$/i

and it should become clear - you need to group those alternatives, otherwise you can match any string that has 'edu' in it, or any string that ends with org. To put it another way, your version matches any of these patterns

  • ^[a-zA-Z0-9]+@[a-zA-Z0-9]\.(com)
  • (edu)
  • (org)$

It's worth pointing out that the original poster is using this as a regex learning exercise. This would be a terrible regex for actual production use! It's a thorny problem - see Using a regular expression to validate an email address for a lot more depth.

like image 76
Paul Dixon Avatar answered Jan 09 '23 21:01

Paul Dixon


Your grouping parentheses are incorrect:

/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.(com|edu|org)$/i

Can also just use one case as you're using the i modifier:

    /^[a-z0-9]+@[a-z0-9]+\.(com|edu|org)$/i

Regular expression visualization

N.B. you were also missing a + from the second set, I assume this was just a typo...

like image 29
SierraOscar Avatar answered Jan 09 '23 21:01

SierraOscar