替换字符如果不匹配

45

我想要一个正则表达式来删除非法字符,但是我不知道这些字符会是什么。

例如:

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


可能是 https://dev59.com/Em865IYBdhLWcg3wYNdS 的重复问题。 - Michael Freidgeim
2个回答

83

那将是:

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

[^ ]在字符类的开头表示对该字符类进行取反 - 它匹配不在该类中的字符。

另请参见:字符类


0

感谢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
              }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接