C# 将字符串替换为'$_';在C中使用正则表达式#
我正在将带分隔符的子字符串从一个字符串复制到另一个字符串。分隔符是#!还有。第一个字符串有我的“不可变内容”,我想把它放在另一个字符串中 例如: 原始字符串:C# 将字符串替换为'$_';在C中使用正则表达式#,c#,regex,C#,Regex,我正在将带分隔符的子字符串从一个字符串复制到另一个字符串。分隔符是#!还有。第一个字符串有我的“不可变内容”,我想把它放在另一个字符串中 例如: 原始字符串: "Lorem Ipsum #! My Immutable Content !# Lorem Ipsum" "Lorem Ipsum #! My Immutable $_ Content !# Lorem Ipsum" 模板字符串: "This is a test #!-!# It worked." 产生: "This is a te
"Lorem Ipsum #! My Immutable Content !# Lorem Ipsum"
"Lorem Ipsum #! My Immutable $_ Content !# Lorem Ipsum"
模板字符串:
"This is a test #!-!# It worked."
产生:
"This is a test #! My Immutable Content !# It worked."
"This is a test #! My Immutable This is a test #!-!# It worked. Content !# It worked."
这个很好用。但是,如果我的原始字符串包含字符串“$\”,则结果字符串是意外的:
原始字符串:
"Lorem Ipsum #! My Immutable Content !# Lorem Ipsum"
"Lorem Ipsum #! My Immutable $_ Content !# Lorem Ipsum"
产生:
"This is a test #! My Immutable Content !# It worked."
"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);
}
string content=“Lorem Ipsum”#!我的不可变$#content!#Lorem Ipsum”;
string template=“这是一个测试!它成功了。”;
Regex regexOld=new Regex(@“(?!(?[\w\d\s.”“\r\n':;\{\\\\[\]\(\)\+\-\*!@$%^&,\?~`\\\\/=]*)!”;
MatchCollection mcOld=regexOld.Matches(内容);
foreach(在mcOld中匹配)
{
Regex regexNew=new Regex(@“(?!(?[\w\d\s.”“\r\n':;\{\\\\[\]\(\)\+\-\*!@$%^&,\?~`\\\\/=]*)!”);
template=regexNew.Replace(template,match.Groups[“all”].Value);
}
我想知道两件事:
$\u
在替换字符串中有特殊含义,它表示输入字符串。要解决您的问题,您可能需要像这样避开它:$\ucode>是的,这解决了我的问题。但是,我在哪里找到了一些关于这方面的文档?用$$替换所有的$是一种通用的解决方案吗?还是只需要替换定义的$number
,${name}
,$&
等。?.NET是否提供了一种方法来进行正则表达式转义?似乎至少没有RegexOption
可以避免这种特殊含义。@ThomasW.:是的,换句话说,当你想在替换模式中使用一个文本$
时,你必须用另一个$
来转义它。