Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do case-insensitive string replacement using regular expressions?

Tags:

c#

.net

regex

I know precisely zilch about regular expressions and figured this was as good an opportunity as any to learn at least the most basic of basics.

How do I do this case-insensitive string replacement in C# using a regular expression?

myString.Replace("/kg", "").Replace("/KG", ""); 

(Note that the '/' is a literal.)

like image 777
Josh Kodroff Avatar asked Jul 16 '09 18:07

Josh Kodroff


People also ask

How do you make a string case insensitive in regex?

To enable the regex case insensitive matching, add (?) prefix or enable the case insensitive flag directly in the Pattern. compile() .

How do you stop case-sensitive in regex?

Case-Sensitive Match To disable case-sensitive matching for regexp , use the 'ignorecase' option.

How do you do case insensitive string comparison?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function.

Can you use regex to replace string?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.


2 Answers

You can use:

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

If you're going to do this a 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 make just that bit of a larger regular expression case insensitive - personally I prefer to use RegexOptions to make an option affect the whole pattern.

MSDN has pretty reasonable documentation of .NET regular expressions.

like image 174
Jon Skeet Avatar answered Oct 04 '22 17:10

Jon Skeet


Like this:

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

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

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

myString = Regex.Replace(myString, "/(?:kg|KG)", String.Empty); 
like image 31
Guffa Avatar answered Oct 04 '22 17:10

Guffa