简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM