我想要一个正则表达式来删除非法字符,但是我不知道这些字符会是什么。
例如:
在一个过程中,我希望我的字符串能够匹配([a-zA-Z0-9/-]*)
。因此,我想替换所有不符合上述正则表达式的字符。
我想要一个正则表达式来删除非法字符,但是我不知道这些字符会是什么。
例如:
在一个过程中,我希望我的字符串能够匹配([a-zA-Z0-9/-]*)
。因此,我想替换所有不符合上述正则表达式的字符。
感谢Kobi的回答,我创建了一个帮助方法来去除不被接受的字符。
允许的模式应该是正则表达式格式,期望它们用方括号括起来。函数将在开放方括号后插入波浪线。我预计它可能无法适用于描述有效字符集的所有正则表达式,但它适用于相对简单的集合,我们正在使用。
/// <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>
/// // https://dev59.com/C2855IYBdhLWcg3wPBtx.
//https://dev59.com/UG025IYBdhLWcg3wNC92
//[^ ] 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
}