3

How can I use the first group in Regex.Replace?
I've tried using $1 like the documentation said. 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?

Simon Woker
  • 4,994
  • 1
  • 27
  • 41

2 Answers2

1

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})"

Also, have you tried

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

Otherwise I don't think c# will know $1 from an ordinary string value

Joanna Derks
  • 4,033
  • 3
  • 26
  • 32
0

This is not the answer to the question you are asking, but to do what you are attempting in your example, you could use HtmlDecode as described here and avoid the whole problem.

Community
  • 1
  • 1
glenatron
  • 11,018
  • 13
  • 64
  • 112