[英]Special signs with Regex Replace
我想用正则表达式替换字符串,但我不能替换正则表达式特殊符号 - 我只想将正则表达式读取^
等作为普通字符串而不是特殊符号。 我试过\\\\
但它仍然无法正常工作。
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()))
您不需要.ToArray
, string.Join
接受IEnumerable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.