0
@"^([a-zA-Z0-9_\-\.\']+)@((\[[0-9]{1,3}" +

              @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

              @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

The regular expression above is used on a C# .net site to validate email addresses. It restricts what comes after the domain to be characters A-Z and can be 2 to 4 letters long.

microsoft.co.uk passes

microsoft.com passes

microsoft.co.fred passes

microsoft.co.freda fails

I need to change the expression so it allows any length strings to occur after the domain.

But if I change the third line to:

@".)+))([a-zA-Z]|[0-9])(\]?)$";

I would have thought that would remove the length restriction. But it doesn't. It makes .com and .co.uk addresses fail.

How can I change the expression to allow:

Jim@somecompany.longwordhere

or

Jim@somecompany.longwordhere.longwordhere

with no restriction on how long 'longwordhere' is and with it being able to be letters or numbers?

Martin Smellworse
  • 1,702
  • 3
  • 28
  • 46
  • Also cosider http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address/1917982#1917982 – Ilia Maskov Apr 22 '15 at 11:47
  • Sidenote: How about switching from regex to, say, [MailAddress](https://msdn.microsoft.com/en-us/library/591bk9e8%28v=vs.110%29.aspx) instead? I know that the "correct" regex for email parsing is [pretty long](http://ex-parrot.com/~pdw/Mail-RFC822-Address.html). – default Apr 22 '15 at 11:47

2 Answers2

1

This is match only 1 character

([a-zA-Z]|[0-9])(\]?)

but this match 1 or more characters

([a-zA-Z]+|[0-9]+)(\]?)

more here : Regex special characters

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
54l3d
  • 3,913
  • 4
  • 32
  • 58
1

I would use this, more concise 3rd line replacement that will also remove length restriction completely with * quantifier:

@".)+))([a-zA-Z0-9]*)(\]?)$";

The can now be 0 or more characters. + requires at least 1. We can safely use * because you have $ end-of-string required anchor.

I'd also use just [a-z] with Ignorecase option, but it is a matter of taste.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563