Yoav
Yoav

Reputation: 2077

Regex.Replace fails on special characters

I'm doing a Replace operation on a large file. I'm having 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 string "BNY MELLON INVESTMENT SERVICING (IN" causes this error:

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

Any way to avoid that?

Upvotes: 4

Views: 1572

Answers (1)

ChaosPandion
ChaosPandion

Reputation: 78252

Fortunately the BCL has your back.

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

Upvotes: 7

Related Questions