0

I am using this regex in .NET to validate email addresses:

([A-Za-z0-9]|[A-Za-z0-9](([\w,=\.!\-#|\$%\^&*\+/\?\{\}~]+)*)[\w,=!\-#|\$%\^&*\+/\?\{\}~])@(?:[A-Za-z0-9-]+\.)+[a-zA-Z]{2,9}$

One issue with it though: In the local name before the @ symbol, it accepts multiple periods in sequence. For example, ab...c@gmail.com.

Does anyone know how I can fix that and yet keep the rest of the logic intact?

Thanks

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
AgentHunt
  • 669
  • 3
  • 11
  • 28
  • 2
    is this another duplicate of your "closed because of duplication" question here http://stackoverflow.com/questions/1263853/regular-expression-for-email-closed – bjelli Aug 12 '09 at 16:28
  • I'm probably just being dense, but where does that regex mention dots? I'm not seeing it. – Michael Myers Aug 12 '09 at 16:32
  • There are 2 unmatched closing brackets. – vit Aug 12 '09 at 16:35
  • Ooops!!! "^([A-Za-z0-9]|[A-Za-z0-9](([\w,=\.!\-#|\$%\^&\*\+/\?`\{\}~]+)*)[\w,=!\-#|\$%\^&\*\+/\?`\{\}~])@(?:[A-Za-z0-9-]+\.)+[a-zA-Z]{2,9}$" Somehow while copying made a mess of it.. Sorry about that! – AgentHunt Aug 12 '09 at 16:37
  • bjelli - That problem was resolved..Its another issue with the same regex. – AgentHunt Aug 12 '09 at 16:38
  • If I "edit" the question, the expression appears correctly ..dont know why:( – AgentHunt Aug 12 '09 at 16:41

2 Answers2

1
while (email.contains(".."))
 email = email.Replace("..",".");
tsilb
  • 7,977
  • 13
  • 71
  • 98
  • Unfortunately I cannot modify the code behind. The only thing I am allowed to change here is the regex :( – AgentHunt Aug 12 '09 at 17:09
1

You can prevent contiguous periods before the '@' the same way you're preventing them after it:

^
[A-Za-z0-9][\w,=!#|$%^&*+/?{}~-]+
(?:\.[A-Za-z0-9][\w,=!#|$%^&*+/?{}~-]+)*
@
(?:[A-Za-z0-9-]+\.)+
[a-zA-Z]{2,9}
$

You'll need to remove the line breaks; I broke it up for readability, since it won't all fit on one line anyway. Got rid of a lot of things that weren't pulling their weight, too.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156