简体   繁体   English

C#Regex.Replace第一组

[英]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, "&lt;font color=&quot;#(?:[\\d\\w]{6})&quot;&gt;", "<font color=\"#$1\">");
// => "<font color=\"#$1\">farbig&lt;/font&gt;"

// this works fine though  
Regex.Match(text, "&lt;font color=&quot;#([\\d\\w]{6})&quot;&gt;").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, "&lt;font color=&quot;#(?:[\\d\\w]{6})&quot;&gt;", "<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM