[英]Strange behavior to replace string with '$_' using Regex in C#
我正在将一个分隔的子字符串从一个字符串复制到另一个字符串。 分隔符是#! 和#!#。 第一个字符串有我的“不可变内容”,我想把它放在另一个字符串中。
例如:
原始字符串:
"Lorem Ipsum #! My Immutable Content !# Lorem Ipsum"
模板字符串:
"This is a test #!-!# It worked."
生产:
"This is a test #! My Immutable Content !# It worked."
这很好用。 但如果我的原始字符串包含字符串'$ _',则结果字符串是意外的:
原始字符串:
"Lorem Ipsum #! My Immutable $_ Content !# Lorem Ipsum"
生产:
"This is a test #! My Immutable This is a test #!-!# It worked. Content !# It worked."
似乎原始字符串都在新字符串中。
产生此结果的代码如下所示
string content = "Lorem Ipsum #! My Immutable $_ Content !# Lorem Ipsum";
string template = "This is a test #!-!# It worked.";
Regex regexOld = new Regex(@"(?<all>#!(?<text>[\w\d\s.""\r\n':;\{\}\[\]\(\)\+\-\*!@#$%^&<>,\?~`_|\\\/=]*)!#)");
MatchCollection mcOld = regexOld.Matches(content);
foreach (Match match in mcOld)
{
Regex regexNew = new Regex(@"(?<all>#!(?<text>[\w\d\s.""\r\n':;\{\}\[\]\(\)\+\-\*!@#$%^&<>,\?~`_|\\\/=]*)!#)");
template = regexNew.Replace(template, match.Groups["all"].Value);
}
我想知道两件事:
$_
在替换字符串中有特殊含义,它表示输入字符串。 要解决您的问题,您可能需要像这样转义: $$_
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.