5

I have a RegularExpressionValidator where the only valid input is 8 characters long and consists of the letters MP followed by six digits. At the moment I have the following regex which does work

^(MP|mp|Mp|mP)[0-9]{6}$

but it feels a bit hacky. I'd like to be able to specify that the MP can be any combination of upper and lower case without having to list the available combinations.

Thanks,

David

dlarkin77
  • 867
  • 1
  • 11
  • 27
  • Possible duplicate of http://stackoverflow.com/questions/2641236/make-regular-expression-case-insensitive-in-asp-net-regularexpressionvalidator – goodeye Feb 24 '13 at 00:25

1 Answers1

3

You can do this when you define Regex object

Regex exp = new Regex(
    @"^mp[0-9]{6}$",
    RegexOptions.IgnoreCase);

Alternatively you can use ^(?i)mp[0-9]{6}$ syntax, which would make just specific bit of regex case-insensitive. But I would personally use the first option (it is easier to read).

For details see documentation on msnd.

oleksii
  • 35,458
  • 16
  • 93
  • 163
  • 1
    +1 but the syntay for inline options would look like this `(?i)` ==> `@"^(?i)(mp)[0-9]{6}$"` – stema Feb 13 '12 at 09:29
  • And I think the OP needed the group just for the alternation, so probably its not needed here, so `@"^mp[0-9]{6}$"` would be fine. – stema Feb 13 '12 at 09:31
  • I'll go with the ?i syntax because I'm not defining any regex objects, I'm setting the regular expression in an ASPX page. – dlarkin77 Feb 13 '12 at 09:33
  • 2
    See answer http://stackoverflow.com/a/3063373/292060 warning that client-side validation won't work for the ?i syntax, since javascript doesn't support mode modifiers. – goodeye Feb 24 '13 at 00:28