[ACCEPTED]-How do you do case-insensitive string replacement using regular expressions?-regex

Accepted answer
Score: 80

You can use:

myString = Regex.Replace(myString, "/kg", "", RegexOptions.IgnoreCase);

If you're going to do this a 5 lot of times, you could do:

// You can reuse this object
Regex regex = new Regex("/kg", RegexOptions.IgnoreCase);
myString = regex.Replace(myString, "");

Using (?i:/kg) would 4 make just that bit of a larger regular expression case 3 insensitive - personally I prefer to use 2 RegexOptions to make an option affect the whole pattern.

MSDN 1 has pretty reasonable documentation of .NET regular expressions.

Score: 6

Like this:

myString = Regex.Replace(myString, "/[Kk][Gg]", String.Empty);

Note that it will also handle 4 the combinations /kG and /Kg, so it does 3 more than your string replacement example.

If 2 you only want to handle the specific combinations 1 /kg and /KG:

myString = Regex.Replace(myString, "/(?:kg|KG)", String.Empty);
Score: 2

"/[kK][gG]" or "(?i:/kg)" will match for 3 you.

declare a new regex object, passing 2 in one of those as your contents. Then run 1 regex.replace.

Score: 0

It depends what you want to achieve. I assume 2 you want to remove a sequence of characters 1 after a slash?

string replaced = Regex.Replace(input,"/[a-zA-Z]+","");

or

string replaced = Regex.Replace(input,"/[a-z]+","",RegexOptions.IgnoreCase);
Score: 0
    Regex regex = new Regex(@"/kg", RegexOptions.IgnoreCase );
    regex.Replace(input, "");

0

Score: 0

Here is an example using the Regex.replace function.

0

More Related questions