替换/删除与正则表达式 (.NET) 不匹配的字符

21

我有一个正则表达式用于验证字符串。但现在我想删除所有与我的正则表达式不匹配的字符。

例如:

regExpression = @"^([\w\'\-\+])"

text = "This is a sample text with some invalid characters -+%&()=?";

//Remove characters that do not match regExp.

result = "This is a sample text with some invalid characters -+";

有什么想法可以使用正则表达式来确定有效字符并删除所有其他字符。

非常感谢

3个回答

23

我相信你可以一行代码实现此功能(允许某些字符,替换其余字符):

var result = Regex.Replace(text, @"[^\w\s\-\+]", "");

从技术上讲,它将生成以下内容: "This is a sample text with some invalid characters - +" 这与您的示例略有不同(在-和+之间多了一个额外的空格)。


如果用于匹配文本的正则表达式更复杂,则此方法将无效。您可以轻松地否定每个正则表达式。 - Daniel Hilgarth
1
真的,但是发帖人说他/她需要基于字符级别的删除,这应该足够了。此外,如果您需要更高的精度,请考虑:var result = Regex.Replace(text, @"[^\w]", m => "%&=?()".Contains(m.Value) ? "" : m.Value); 您可以用任何代码替换我的MatchEvaluator来确定是否保留字符。 - emfurry

17

就是这么简单:

var match = Regex.Match(text, regExpression);
string result = "";
if(match.Success)
    result = match.Value;

删除不匹配的字符等同于保留匹配的字符。这就是我们在这里所做的。

如果你的文本中可能存在多次匹配表达式的情况,你可以使用以下方法:

var result = Regex.Matches(text, regExpression).Cast<Match>()
                  .Aggregate("", (s, e) => s + e.Value, s => s);

嗨,丹尼尔,我尝试了你的解决方案,但正如你所提到的,我的正则表达式会匹配多次,因为我需要它只删除无效字符,但保留所有有效字符。我无法使用第二段代码,在Cast<Match>()中出现错误。我应该用其他东西替换那部分还是按照你输入的代码使用它。谢谢。 - tif
(1) 你提供的正则表达式没有按照你的期望执行。(2) 你得到了什么错误?我实际上测试过那段代码,它是有效的。 - Daniel Hilgarth
(1) 正则表达式为什么有问题?或者应该怎么做?我在一个类似的方法中使用相同的正则表达式,只是验证它是否是有效的字符串,但这个新方法不是返回true,而是删除/替换无效字符,我猜我需要使用两个不同的正则表达式,因为一个不能同时适用于两种情况,对吗? (2) 我忘记添加 System.Linq 指令了。 - tif
正则表达式匹配一个单词或者以下字符之一:' - + 在行首 - Daniel Hilgarth
我已经在评论中提到了emfurry的方法存在的问题。 - Daniel Hilgarth
显示剩余5条评论

3
感谢Replace chars if not match的答案,我创建了一个辅助方法来去除不被接受的字符
允许的模式应该是正则表达式格式,期望它们包含在方括号中。函数将在开方括号后插入一个波浪线。我预计它可能无法处理描述有效字符集的所有正则表达式,但它适用于相对简单的集合,这是我们正在使用的。
 /// <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;
              }

static public string RemoveNonAlphanumericCharacters( this string text)
              {
                      var result = text.ReplaceNotExpectedCharacters(NonAlphaNumericCharacters, "" );
                      return result;
              }
        public const string NonAlphaNumericCharacters = "[a-zA-Z0-9]";

这里使用了我 StringHelper 类中的几个函数 http://geekswithblogs.net/mnf/archive/2006/07/13/84942.aspx

           /// <summary>
           /// ‘StripBrackets checks that starts from sStart and ends with sEnd (case sensitive).
           ///           ‘If yes, than removes sStart and sEnd.
           ///           ‘Otherwise returns full string unchanges
           ///           ‘See also MidBetween
           /// </summary>

           public static string StripBrackets( this string str, string sStart, string sEnd)
          {
                  if (CheckBrackets(str, sStart, sEnd))
                 {
                       str = str.Substring(sStart.Length, (str.Length – sStart.Length) – sEnd.Length);
                 }
                  return str;
          }
           public static bool CheckBrackets( string str, string sStart, string sEnd)
          {
                  bool flag1 = (str != null ) && (str.StartsWith(sStart) && str.EndsWith(sEnd));
                  return flag1;
          }

它没有回答如何替换/删除不在匹配组中的字符。 - AuthorProxy
注意:函数StripBrackets未提供。而@"[^" + allowedPattern + "]"对于任意模式都不起作用,但对于简单情况来说,这是一个不错的解决方案。 - shelbypereira
@shelbypereira,StripBrackets是在一个链接的文章中提到的,我现在已经将其添加到答案中了。 - Michael Freidgeim

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