【发布时间】: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 => Regex.Escape(k.ToString()))(甚至不确定您是否需要.ToString()) -
好的,谢谢我改成
return Regex.Replace(source, string.Join("|", xmlEntityReplacements.Keys.Select(k => Regex.Escape(k.ToString())).ToArray()), m => xmlEntityReplacements[m.Value]);,现在它可以工作了:)