【问题标题】:Special signs with Regex Replace带有正则表达式替换的特殊符号
【发布时间】:2020-03-29 20:30:24
【问题描述】:

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

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

【问题讨论】:

  • 您不需要在键上添加反斜杠,而是使用Regex.Escape 动态转义它们,例如xmlEntityReplacements.Keys.Select(k =&gt; Regex.Escape(k.ToString()))(甚至不确定您是否需要.ToString()
  • 好的,谢谢我改成return Regex.Replace(source, string.Join("|", xmlEntityReplacements.Keys.Select(k =&gt; Regex.Escape(k.ToString())).ToArray()), m =&gt; xmlEntityReplacements[m.Value]); ,现在它可以工作了:)

标签: c# regex replace


【解决方案1】:

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

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

您也不需要.ToArraystring.Join acceptsIEnumerable

【讨论】:

  • 顺便说一句,我有一个问题/使用正则表达式更快,或者只是多次使用 string.replace()?
  • @ps-create 您可以在自己的环境中对实际数据进行测试。如果你follow the guidelines on regex usage,正则表达式解决方案可能会尽可能快,因为字符串只会被处理一次。
猜你喜欢
  • 1970-01-01
  • 2015-12-23
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多