在 C# 中使用正则表达式将字符串替换为“$_”的奇怪行为
本文关键字:替换 正则表达式 字符串 | 更新日期: 2023-09-27 17:56:26
>我正在将分隔的子字符串从一个字符串复制到另一个字符串。分隔符是 #!和 !#。第一个字符串有我的"不可变内容",我想把它放在另一个字符串中。
例如:
原始字符串:
"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);
}
我想知道两件事:
- 为什么字符串"$_"会导致此行为?
- 如何解决这个问题?
$_
替换字符串中具有特殊含义,它表示输入字符串。要解决您的问题,您可能需要像这样逃避它:$$_