Благодаря ответу Коби я создал вспомогательный метод для удаления недопустимых символов .
Допустимый шаблон должен быть в формате Regex, ожидайте, что он будет заключен в квадратные скобки. Функция вставит тильду после открытия скобки.
Я предполагаю, что он может работать не для всех RegEx, описывающих допустимые наборы символов, но он работает для относительно простых наборов, которые мы используем.
/// <summary>
/// Replaces not expected characters.
/// </summary>
/// <param name="text"> The text.</param>
/// <param name="allowedPattern"> The allowed pattern in Regex format, expect them wrapped in brackets</param>
/// <param name="replacement"> The replacement.</param>
/// <returns></returns>
/// // /3373138/zamenit-simvoly-esli-oni-ne-sovpadayt.
//https://stackoverflow.com/questions/6154426/replace-remove-characters-that-do-not-match-the-regular-expression-net
//[^ ] at the start of a character class negates it - it matches characters not in the class.
//Replace/Remove characters that do not match the Regular Expression
static public string ReplaceNotExpectedCharacters( this string text, string allowedPattern,string replacement )
{
allowedPattern = allowedPattern.StripBrackets( "[", "]" );
//[^ ] at the start of a character class negates it - it matches characters not in the class.
var result = Regex.Replace(text, @"[^" + allowedPattern + "]", replacement);
return result; //returns result free of negated chars
}