我正在查找删除非法字符的正则表达式。但我不知道角色会是什么。如果不匹配,则替换字符
例如:
在一个过程中,我想我的字符串匹配([a-zA-Z0-9/-]*)
。所以我想替换不匹配的所有字符上面的正则表达式。
我正在查找删除非法字符的正则表达式。但我不知道角色会是什么。如果不匹配,则替换字符
例如:
在一个过程中,我想我的字符串匹配([a-zA-Z0-9/-]*)
。所以我想替换不匹配的所有字符上面的正则表达式。
由于Kobi的答案,我已经创建了一个helper method to strips unaccepted characters。
允许的模式应该是正则表达式格式,期望它们被包裹在方括号中。打开squere括号后,函数将插入波形符号。 我预计它不能用于描述有效字符集的所有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>
/// // https://stackoverflow.com/questions/4460290/replace-chars-if-not-match.
//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
}
可能的重复http://stackoverflow.com/questions/3847294/replace-all-characters-not-in-range-java-string – 2012-08-30 14:30:04