Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex.Replace first group

Tags:

c#

regex

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?

like image 292
Simon Woker Avatar asked Apr 19 '26 21:04

Simon Woker


1 Answers

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

like image 187
Joanna Derks Avatar answered Apr 22 '26 19:04

Joanna Derks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!