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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

hmm, looks like my example without ?: was messed up in some other way.. thanks!
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.

1 Comment

The problem is that I'm using HTMLEncode and only Decode specific tags like b, i, u, br, hr and font.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.