views:

138

answers:

3

Given this regular expression: "^[0-9]*\s*(lbs|kg|kgs)$" how do I make it case insensitive? I am trying to use this in a .net regular expression validator, so I need to specify case insensitivity in the pattern.

I can not use the RegexOptions programatically because I am specifying the regular expression in a RegularExpressionValidator

+4  A: 

Use RegEx Options.

Regex regExInsensitive = new Regex(@"^[0-9]\s(lbs|kg|kgs)$", RegexOptions.IgnoreCase);

In other languages you can usually specify a RegEx modifier after the end of the Reg Ex; the 'case insensitive' modifier is 'i':

In Perl:

if($var =~ /^[0-9]\s(lbs|kg|kgs)$/i) { # the /i means case insensitive
    # ...
}

In PHP:

if(preg_match("/^[0-9]\s(lbs|kg|kgs)$/i", $var)) {
    // ...
}
LeguRi
I'm using dot net, and can not specify RegexOptions because I'm not instantiating a Regex object, I'm specifying the regular expression in a RegularExpressionValidator
Jeremy
All right then; reading fail for me :( However, if you're "not using .NET" then why is the question tagged as dotnet? Is "dotnet" something else? Also, what is 'RegularExpressionValidator'? Is it a tool? A type? A library?
LeguRi
@Richard, that's a component in ASP.NET, see http://msdn.microsoft.com/en-us/library/eahwtc9e.aspx The documentation says that the same regular expression is used on the server side and the client side, so the regular expression should also be valid for javascript as well as .NET. Otherwise it could just use (?i) at the beginning to make it case insensitive.
Geoff Reedy
+2  A: 

Easiest here is to just modify the regex to

^[0-9]*\s*([lL][bB][sS]|[kK][gG][sS]?)$

It's awful to read, but it will work fine.

Geoff Reedy
+1  A: 

I found out.

Case sensitive: ^[0-9]\s(lbs|kg|kgs)$

Case insensitive: (?i:^[0-9]\s(lbs|kg|kgs)$)

I believe that this is specific to the .net implementation of regular expressions. So if you use this in the RegularExpressionValidator you have to turn off client side validation because the javascript regex parser will not recognize the ?i token.

Jeremy
Actually, most of the language-embedded flavors *do* support inline modifiers like `(?i)`: Perl, Python, PHP, Ruby, Java, .NET... JavaScript is the last holdout, and it's a right pain in the butt! BTW, @Geoff did mention `(?i)` in a comment.
Alan Moore