Home > Software engineering >  Why is Regex.Replace with RegexOptions.IgnoreCase not working when I have "(" in the text?
Why is Regex.Replace with RegexOptions.IgnoreCase not working when I have "(" in the text?

Time:12-21

I want to replace text with Regex, and to use RegexOptions.IgnoreCase, but it is not working, when I have "(" in my text.

The code is:

var textToReplace = @" = CreateObject""(ADODB.Recordset)"";";
var retval = @"  RsBO = CreateObject""(adodb.recordset)"";";
var Newtext = " = new Recordset();";
Regex regexText = new Regex(textToReplace, RegexOptions.IgnoreCase);
retval = regexText.Replace(retval, Newtext);

The result is:

RsBO = CreateObject\"(adodb.recordset)\";

But I want to see:

RsBO = new Recordset();

If I remove the chars '(' and ')', it works.

CodePudding user response:

There are a few special characters in your expression:

( and ) delimits a capture group, while . represents any character (except line terminators).

Try escaping ), ( and .:

var textToReplace = @" = CreateObject""\(ADODB\.Recordset\)"";";

CodePudding user response:

The intended replacement does not need a Regex at all because the string you are searching for does not use any of the pattern-matching features of a regular expression.

There is an overload of string.Replace where you can specify a string comparer which allows to do a case-insensitive match:

retval = retval.Replace(textToReplace, Newtext, StringComparison.OrdinalIgnoreCase);
  • Related