36

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

6 Answers 6

84

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You left out the colon: (?i:/kg)
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);

Comments

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.

Comments

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

Comments

0
    Regex regex = new Regex(@"/kg", RegexOptions.IgnoreCase );
    regex.Replace(input, "");

4 Comments

see Jon Skeet below, he posted first
No need for @ when there are only forward slashes.
yeah, I used nregex.com to create the first line of the example. they use the @ regardless of the pattern
If you always prefix regular expressions with @, you never have to think about whether or not a given one requires it.
0

Here is an example using the Regex.replace function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.