Regex.Replace does not work with special characters

I am doing a Replace operation in a large file. I have a problem with the '(' character. This is my method:

public static string Replace(string input, string stringToMask, string mask) { return Regex.Replace(input, @"(?<![0-9])" + stringToMask + "(?![0-9])", mask); } 

This line "BNY MELLON INVESTMENT SERVICING (IN) causes this error:

 parsing "(?<![0-9])BNY MELLON INVESTMENT SERVICING (IN(?![0-9])" - Not enough )'s. 

How to avoid this?

+4
source share
1 answer

Fortunately, BCL has a back.

 var pattern = @"(?<![0-9])" + Regex.Escape(stringToMask) + "(?![0-9])"; return Regex.Replace(input, pattern, mask); 
+7
source

All Articles