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

105 views Asked by At

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.

2

There are 2 answers

1
Anderson Pimentel On

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\)"";";
0
Klaus Gütter On

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