从 C# 中的字符串中删除特殊字符的列表

本文关键字:特殊字符 列表 删除 字符串 | 更新日期: 2023-09-27 17:56:16

我需要用要字符串的特定特殊字符列表替换字符串。空。

示例:123 ~主到 123 主

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

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

> 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);

提前谢谢。

从 C# 中的字符串中删除特殊字符的列表

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

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))))));

稍微干净的正则表达式(仅转义方括号之间的元字符) - [+!(){}[']'^~*?:''"]|&&|'|'| .

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

试试这个...

        //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_]+", " ");
另一个

使用 LINQ 的"漂亮"解决方案:

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

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

你可以

在这里使用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();

如果你想这么糟糕地使用替换函数,那就这样做:

string[] replaceables = new[] { "+", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^", "~", "*", "?", ":", "''", "'"" };
for(int i = 0; i < replaceables.lenght; i++)
{
  myString = myString.replace(replaceables[i], String.Empty);
}
  • 从@Ulugbek乌米罗夫复制的数组"字符串[] 可替换项"