如果不匹配则替换字符

时间:2010-12-16 11:29:19

标签: regex illegal-characters

我正在寻找一个删除非法字符的正则表达式。但我不知道角色会是什么。

例如:

在一个过程中,我希望我的字符串与([a-zA-Z0-9/-]*)匹配。所以我想替换不匹配上面的正则表达式的所有字符。

2 个答案:

答案 0 :(得分:44)

那将是:

[^a-zA-Z0-9/-]+

[^ ]在一个字符类的开头否定它 - 它匹配不在类中的字符。

另请参阅:Character Classes

答案 1 :(得分:-1)

感谢Kobi的答案,我创建了helper method to strips unaccepted characters

允许的模式应该是Regex格式,期望它们用方括号括起来。打开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
              }