c# - 带有正则表达式替换的特殊符号
问题描述
我想用正则表达式替换字符串,但我不能替换正则表达式特殊符号 - 我只想将正则表达式读取^
等作为普通字符串而不是特殊符号。我试过\\
了,但还是不行。
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
。
推荐阅读
- amazon-web-services - 缺少 AWS Glue 版本 2.0 ETL 作业的执行程序 CloudWatch 日志
- ruby-on-rails - 在 XHR 响应后加载 javascript 包
- sql - 每个月的第一个星期一截断表
- c - 如何在 WSL2 上正确安装 perf 命令
- python - 对 websocket 服务器的请求失败并出现 WebSocket I/O 错误:读取超时
- typescript - 找不到模块“is_js”的声明文件
- python - How to restrict number of elements in list while doing itertools.combinations?
- angular - Angular RXJS 需要了解服务是如何工作的
- wordpress - 每个类别仅显示最近更新的一篇文章
- python - 在数据框中的列中手动排序字符串