Replace named group in regex

Posted by Tomas Voracek on Stack Overflow See other posts from Stack Overflow or by Tomas Voracek
Published on 2010-04-16T21:07:12Z Indexed on 2010/04/16 21:13 UTC
Read the original article Hit count: 393

Filed under:
|

I want to use regular expression same way as string.Format. I will explain

I have:

string pattern = "^(?<PREFIX>abc_)(?<ID>[0-9])+(?<POSTFIX>_def)$";
string input = "abc_123_def";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
string replacement = "456";
Console.WriteLine(regex.Replace(input, string.Format("${{PREFIX}}{0}${{POSTFIX}}", replacement)));

This works, but i must provide "input" to regex.Replace. I do not want that. I want to use pattern for matching but also for creating strings same way as with string format, replacing named group "ID" with value. Is that possible?

I'm looking for something like:

string pattern = "^(?<PREFIX>abc_)(?<ID>[0-9])+(?<POSTFIX>_def)$";
string result = ReplaceWithFormat(pattern, "ID", 999);

Result will contain "abc_999_def". How to accomplish this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about regex