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.)
To enable the regex case insensitive matching, add (?) prefix or enable the case insensitive flag directly in the Pattern. compile() .
Case-Sensitive Match To disable case-sensitive matching for regexp , use the 'ignorecase' option.
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.
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.
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 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With