12

I want to validate an email address with Regex in C#.

I'm using this pattern:

^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

This pattern only matches upper case letters. For example:

"[email protected]" --> returns false. "[email protected]" --> returns true.

I obviously would like that the first example will also return true.

NOTE: I DON'T want to use the RegexOptions.IgnoreCase flag.

I would like to change the pattern itself to match the first example. I think that I can add a "/i" in the end of the pattern or something like this but it doesn't seems to work. I prefer not to use the "?i" in the beginning as well.

How can i achieve this?

(If you could rewrite the whole pattern for me, it would be great!).

Thanks.

4
  • 4
    How is PCRE's i modifier any better than .NET's RegexOptions.IgnoreCase? Is it because it's 22 characters less to type? Commented Jan 26, 2011 at 8:49
  • Be careful about the . in the [] block, if you don't want to match any character escape it with a \ Commented Jan 26, 2011 at 8:57
  • 1
    @Johann characters don't need escaping within [] blocks (at least in the .NET regex syntax). Commented Jan 26, 2011 at 9:01
  • 1
    Be aware that TLD may have more than 4 character long like travel or museum Commented Jan 26, 2011 at 11:03

3 Answers 3

24

Instead of just [A-Z], use [A-Za-z].

But watch out: there are e-mail addresses that end in top-level domains like .travel, that are forbidden according to your regex!

Sign up to request clarification or add additional context in comments.

Comments

20

You can just use: ^(?i)[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

Notice the (?i) which sets the RegexOptions.IgnoreCase, this way you wont have to modify any character classes in the regex or modify where the code is used.

Example (In F# interactive):

Regex.Match("[email protected]", @"^(?i)[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$");;
val it : Match = [email protected] {Captures = seq [...];
                              Groups = seq [...];
                              Index = 0;
                              Length = 13;
                              Success = true;
                              Value = "[email protected]";} 

1 Comment

I like it - Using the i modifier to set .ignoreCase is much better than setting .ignoreCase in your code. Using the i means if your regex is stored in a settings file or database you can change it easily.
6

Well, this would work.

^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}$

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.