首页 > 解决方案 > 带有正则表达式替换的特殊符号

问题描述

我想用正则表达式替换字符串,但我不能替换正则表达式特殊符号 - 我只想将正则表达式读取^等作为普通字符串而不是特殊符号。我试过\\了,但还是不行。

public static string ReplaceXmlEntity(string source)
{
    if (string.IsNullOrEmpty(source)) return source;
    var xmlEntityReplacements = new Dictionary<string, string>
    {
        // Find all the original spaces and replace with a space
        // and placemarker for the space
        {" ", " ^"},
        {" \\^ \\^", " ^"},
        // Find all the double quotes and replace with placemarker 
        {"''", " ~ "},
        // Add extra spaces around key values so they can be isolated in
        // into their own array slots
        {",", " , "},
        {"'", " ' " },
        {"'('", " ( " },
        {"')'", " ) " },
        // Replace all the special characters and extra spaces
        {"\n", " 0x000A " },
        {"\r", " 0x000D " },
        {"\t", " 0x0009 " },
        {"\v", " 0x000B " },
    };
    return Regex.Replace(source, string.Join("|", xmlEntityReplacements.Keys
        .Select(k => k.ToString()).ToArray()), m => xmlEntityReplacements[m.Value]);
}

标签: c#regexreplace

解决方案


当您转义字典键中的特殊字符时,您将无法再访问它们,除非您取消转义匹配项,但这可能会导致其他问题。这意味着您应该使用Regex.Escape单独转义每个字典键:

xmlEntityReplacements.Keys.Select(k => Regex.Escape(k.ToString()))

你不需要.ToArray,也string.Join接受一个IEnumerable


推荐阅读