[英]C# Regex.Replace first group
How can I use the first group in Regex.Replace? 如何在Regex.Replace中使用第一组?
I've tried using $1
like the documentation said. 我试过像文件说的那样使用$1
。 Also it doesn't matter if I use grouping with ?:
or not... 如果我使用?:
分组也没关系... ?:
或者不...
string text = "<font color="#aa66bb">farbig</font>"
/// this does not work
Regex.Replace(text, "<font color="#(?:[\\d\\w]{6})">", "<font color=\"#$1\">");
// => "<font color=\"#$1\">farbig</font>"
// this works fine though
Regex.Match(text, "<font color="#([\\d\\w]{6})">").Groups[1];
// => aa66bb
So what am I doing wrong here? 那么我在这里做错了什么?
Could it be just that you are using a non-capturing group here? 难道只是你在这里使用非捕获组吗?
Regex.Replace(this.Text, "<font color="#(?:[\\d\\w]{6})">", "<font color=\"#$1\">");
it is: 它是:
(?:[\\d\\w]{6})
instead of 代替
([\\d\\w]{6})
You can use @ btw to escape all the special chars: @"(?:[\\d\\w]{6})"
您可以使用@ btw来逃避所有特殊字符: @"(?:[\\d\\w]{6})"
Also, have you tried 还有,你试过吗?
"<font color=\"#" + $1 + "\">"
Otherwise I don't think c# will know $1 from an ordinary string value 否则我不认为c#会从普通的字符串值知道$ 1
这不是回答你问的问题,而是你正试图在你的例子是什么,你可以使用HtmlDecode
描述这里和避免整个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.