C # Regex. Replace first group

How can I use the first group in Regex.Replace?
I tried using $1as documentation . It also doesn't matter if I'm using 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?

+3
source share
2 answers

Maybe you use a group here without capture?

Regex.Replace(this.Text, "&lt;font color=&quot;#(?:[\\d\\w]{6})&quot;&gt;", "<font color=\"#$1\">");

this:

(?:[\\d\\w]{6})

instead

([\\d\\w]{6})

You can use @btw to avoid all special characters: @"(?:[\d\w]{6})"

Also, have you tried

"<font color=\"#" + $1 + "\">"

Otherwise, I do not think C # will know $ 1 from the usual string value

+1
source

, , , , HtmlDecode, , .

0

All Articles