【问题标题】:Replace chars if not match如果不匹配则替换字符
【发布时间】:2023-12-27 22:12:02
【问题描述】:

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

例如:

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

【问题讨论】:

标签: regex illegal-characters


【解决方案1】:

那就是:

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

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

另见:Character Classes

【讨论】:

    【解决方案2】:

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

    允许的模式应该是正则表达式格式,期望它们用方括号括起来。一个函数将在打开方括号后插入一个波浪号。 我预计它不适用于所有描述有效字符集的 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://*.com/questions/4460290/replace-chars-if-not-match.
                   //https://*.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
                  }
    

    【讨论】:

      最近更新 更多