在C#中从字符串中删除一系列特殊字符

3

我需要将一个字符串中的特定一组特殊字符替换为string.Empty。

例如:123 ~Main To 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 - Ulugbek Umirov
5个回答

7
你可以动态构建正则表达式 - \+|&&|\|\||!|\(|\)|\{|}|\[|]|\^|~|\*|\?|:|\\|":
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

仅供参考,为了性能问题,使用[...]而不是长的.|...|.通常更快地匹配一个字符模式。 - Robin
@Robin 他有多个字符模式。 - Ulugbek Umirov
1
是的,我知道。混合两种方法将是最佳选择:类似于 [-+!(){}\[\]^\"~*?:\\]|\|\||&& 的东西。 - Robin
@Robin,根据你的建议,我添加了生成函数。 - Ulugbek Umirov

1
尝试这个...
        //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_]+", " ");

你为什么在最后一个字符类中添加了“_”?另外,我不确定(需要向原始发布者澄清吗?)是否应该匹配单个“|”。 - Robin

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

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

但我认为使用正则表达式会在性能方面更有效的解决办法(特别是如果你的字符串很长)。


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

1

如果你非常想使用替换函数,那么可以这样做:

string[] replaceables = new[] { "+", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^", "~", "*", "?", ":", "\\", "\"" };

for(int i = 0; i < replaceables.lenght; i++)
{
  myString = myString.replace(replaceables[i], String.Empty);
}
  • 从@Ulugbek Umirov复制的数组 "string[] replaceables"

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