Martin Smellworse
Martin Smellworse

Reputation: 1762

Modify regular expression to not check length

@"^([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:

[email protected]

or

[email protected]

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

Upvotes: 0

Views: 65

Answers (2)

54l3d
54l3d

Reputation: 3973

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

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

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.

Upvotes: 1

Related Questions