【问题标题】:Remove a list of special characters from string in C# [duplicate]从C#中的字符串中删除特殊字符列表[重复]
【发布时间】:2014-05-14 21:14:50
【问题描述】:

我需要用特定的特殊字符列表替换一个字符串到 string.Empty。

示例:123 ~Main 到 123 Main

特殊字符列表:+ - && || ! ( ) { } [ ] ^ " ~ * ? : \

我知道我们可以在下面这样做,我们能不能有更好的方法,使用一些正则表达式。

> keyword = keyword.Replace("+", string.Empty);
>         keyword = keyword.Replace("&&", string.Empty);
>         keyword = keyword.Replace("||", string.Empty);
>         keyword = keyword.Replace("!", string.Empty);
>         keyword = keyword.Replace("(", string.Empty);
>         keyword = keyword.Replace(")", string.Empty);
>         keyword = keyword.Replace("{", string.Empty);
>         keyword = keyword.Replace("}", string.Empty);
>         keyword = keyword.Replace("[", string.Empty);
>         keyword = keyword.Replace("]", string.Empty);
>         keyword = keyword.Replace("^", string.Empty);
>         keyword = keyword.Replace("~", string.Empty);
>         keyword = keyword.Replace("*", string.Empty);
>         keyword = keyword.Replace("?", string.Empty);
>         keyword = keyword.Replace(":", string.Empty);
>         keyword = keyword.Replace("\\", string.Empty);
>         keyword = keyword.Replace("\"", string.Empty);

提前致谢。

【问题讨论】:

  • 字符串Hello |*| world 的预期行为是什么?如果我们先替换|| 然后*,我们得到Hello || world,如果我们做相反的事情,我们得到Hello world

标签: c# regex


【解决方案1】:

您可以即时构建正则表达式 - \+|&&|\|\||!|\(|\)|\{|}|\[|]|\^|~|\*|\?|:|\\|":

string input = "Hello world!";
string[] replaceables = new[] { "+", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^", "~", "*", "?", ":", "\\", "\"" };
string rxString = string.Join("|", replaceables.Select(s => Regex.Escape(s)));
string output = Regex.Replace(input, rxString, string.Empty);

您还可以按照@Robin 的建议优化正则表达式(尽管生成变得复杂)-[\+!\(\)\{}\[\]\^~\*\?:\\"]|&&|\|\|

string rxString = string.Join("|", replaceables.GroupBy(r => r.Length > 1)
                                               .Select(g => g.Key ? string.Join("|", g.Select(r => Regex.Escape(r)))
                                                                  : string.Format("[{0}]", string.Join(string.Empty, g.Select(r => r == "]" ? "\\]" : Regex.Escape(r))))));

更简洁的正则表达式(只有方括号之间的metacharacters 被转义)-[+!(){}[\]\^~*?:\\"]|&&|\|\|

string rxString = string.Join("|", replaceables.GroupBy(r => r.Length > 1)
                                               .Select(g => g.Key ? string.Join("|", g.Select(r => Regex.Escape(r)))
                                                                  : string.Format("[{0}]", string.Join(string.Empty, g.Select(r => new[] { "]", @"\", "-", "^" }.Contains(r) ? @"\" + r : r)))));

尽可能干净的正则表达式(对转义元字符的要求进行额外验证)-[+!(){}[\]^~*?:\\"]|&&|\|\|

string rxString = string.Join("|", replaceables.GroupBy(r => r.Length > 1)
                                               .Select(g => g.Key ? string.Join("|", g.Select(r => Regex.Escape(r)))
                                                                  : string.Format("[{0}]", string.Join(string.Empty, g.Select((r, i) => r == @"\" || r == "]" && g.Count() > 1 || r == "^" && i == 0 || r == "-" && i > 0 ? @"\" + r : r)))));

如果你有Hello &|&&|& complicated world!这样的字符串,那么你需要传递几次。

string output = input;
string outputRef = output;
do
{
    outputRef = output;
    output = Regex.Replace(output, rxString, string.Empty);
} while (output != outputRef);
Console.WriteLine(output); // Hello  complicated world

【讨论】:

  • 仅供参考,对于性能问题,使用 [...] 而不是长 .|...|. 通常更快地匹配一个字符模式。
  • @Robin 他有多个字符模式。
  • 是的,我知道。混合这两种方法将是最佳方法:[-+!(){}\[\]^\"~*?:\\]|\|\||&&
  • @Robin 我根据你的建议添加了生成功能。
【解决方案2】:

试试这个...

        //to remove non alphanumeric characters (special characters) from a string?
        public static string removespclchr(string input)
        {
            Regex regex = new Regex("[^a-zA-Z0-9]");
            return regex.Replace(input, "");
        }

string q = Regex.Replace(query, @""|['"",&?%\.*:#/\\-]", " ").Trim();

string replacestr= Regex.Replace(str, "[^a-zA-Z0-9_]+", " ");

【讨论】:

  • 为什么在最后一个字符类中添加_?另外我不确定(要与 OP 澄清?)应该匹配单个 |
【解决方案3】:

另一个使用 LINQ 的“漂亮”解决方案:

const string input = "+Hello world!-&&-Hey!";
string[] replaceables = { "+", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^", "~", "*", "?", ":", "\\", "\"" };
var cleanInput = replaceables.Aggregate(input, (result, item) => result.Replace(item, string.Empty));

但我想使用正则表达式在性能方面会是更有效的解决方案(尤其是如果您的字符串很大)。

【讨论】:

    【解决方案4】:

    您可以在这里使用StringBuilder

    string str = "+ - && || ! ( ) { } [ ] ^ \" ~ * ? : \\";
    string[] array = str.Split();
    
    string s = "123 ~Main";
    
    StringBuilder sb = new StringBuilder();
    foreach (var c in s)
    {
        sb = array.Contains(c.ToString()) ? sb.Append("") : sb.Append(c);
    }
    
    Console.WriteLine(sb.ToString()); // 123 Main
    Console.ReadLine();
    

    【讨论】:

      【解决方案5】:

      如果你想使用替换功能那么糟糕,那就这样做吧:

      string[] replaceables = new[] { "+", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^", "~", "*", "?", ":", "\\", "\"" };
      
      for(int i = 0; i < replaceables.lenght; i++)
      {
        myString = myString.replace(replaceables[i], String.Empty);
      }
      
      • 从@Ulugbek Umirov 复制的数组“string[] replaceables”

      【讨论】:

        猜你喜欢
        • 2014-05-20
        • 1970-01-01
        • 2019-11-09
        • 2015-01-13
        • 2020-11-19
        • 2012-12-16
        • 1970-01-01
        • 1970-01-01
        • 2019-12-22
        相关资源
        最近更新 更多