Khalid Omar
Khalid Omar

Reputation: 2402

ignore case sensitive in regex.replace?

I have this code to search in a string and replace some text with other text:

Regex regexText = new Regex(textToReplace);
retval = regexText.Replace(retval, Newtext);

textToReplace may be "welcome" or "client" or anything.

I want to ignore case for textToReplace so that "welcome" and "Welcome" both match.

How can I do this?

Upvotes: 7

Views: 15275

Answers (3)

You simply pass the option RegexOptions.IgnoreCase like so:

Regex regexText = new Regex(textToReplace, RegexOptions.IgnoreCase);
retval = regexText.Replace(retval, Newtext);

Or, if you prefer, you can pass the option directly to the Replace method:

retval = Regex.Replace(retval, textToReplace, Newtext, RegexOptions.IgnoreCase);

A list of the available options you can set for regexes is available at the RegexOptions documentation page.

Upvotes: 15

petro.sidlovskyy
petro.sidlovskyy

Reputation: 5093

You may try:

Regex regexText = new Regex(textToReplace, RegexOptions.IgnoreCase);

Upvotes: 20

Hans Kesting
Hans Kesting

Reputation: 39265

There's a Regex.Replace overload with RegexOptions. Those options include an IgnoreCase value.

Upvotes: 1

Related Questions