Perform an operation on the Named Capture group in regex.Replace

I apologize in advance if this is a duplicate. I can’t imagine that they didn’t ask him before, but I couldn’t find him.

Why does the second C # operator throw an exception?

var regex = new Regex(@"\[IMG(?<image_number>[0-9]+)\]"); regex.Replace("[IMG1]", int.Parse("${image_number}").ToString()); 

I know that I can access a named group, but I cannot perform an operation on it - in this case int.Parse (). When I try to use a named group this way, it just gives me the string "$ {image_number}" - which, of course, cannot be parsed as an integer.

Thanks.

+4
source share
1 answer

The Regex class is not magic.

It cannot magically insert the captured value into string literals that appear inside Replace calls.
Instead, if you pass the string that refers to the capture group to the Replace() method, it will parse the string and enter the value.

You need to pass the lambda expression :

 regex.Replace("[IMG1]", m => int.Parse(m.Groups["image_number"].Value).ToString()); 
+2
source

All Articles