33

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.)

Benjamin Autin
  • 4,143
  • 26
  • 34
Josh Kodroff
  • 27,301
  • 27
  • 95
  • 148

6 Answers6

81

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.

Sachin Joseph
  • 18,928
  • 4
  • 42
  • 62
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

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);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Why the downvote? If you don't explain what you think is wrong, it can't improve the answer. – Guffa Aug 28 '12 at 23:03
2

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

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

tom.dietrich
  • 8,219
  • 2
  • 39
  • 56
0

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

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

or

string replaced = Regex.Replace(input,"/[a-z]+","",RegexOptions.IgnoreCase);
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
0
    Regex regex = new Regex(@"/kg", RegexOptions.IgnoreCase );
    regex.Replace(input, "");
Tim Hoolihan
  • 12,316
  • 3
  • 41
  • 54
0

Here is an example using the Regex.replace function.

Brad
  • 639
  • 1
  • 9
  • 23