It sounds like you're looking for the Replace
method with an overload that accepts a MatchEvaluator. The MSDN page for that method can be found here.
Try this instead:
string input = "[img]http://imagesource.com[/img]";
string pattern = @"\[img]([^\]]+)\[\/img]";
string result = Regex.Replace(input, pattern, m =>
{
var url = m.Groups[1].Value;
// do something with url here
// return the replace value
return @"<img src=""" + url + @""" border=""0"" />";
},
RegexOptions.IgnoreCase);
This uses a multi-statement lambda to simplify working with the group and performing more logic before returning the replacement value. You could, of course, get away with this instead:
string result = Regex.Replace(input, pattern,
m => @"<img src=""" + m.Groups[1].Value + @""" border=""0"" />",
RegexOptions.IgnoreCase);
In the above case there's no need for the return
but it's just returning the original string without additional evaluation. You could stick some ternary operators and add that logic, but it'll look messy. A multi-statement lambda is much cleaner. You may consider breaking it out in its own method, as shown in the aforementioned MSDN link, if it is too large or will be reused in other Regex.Replace
efforts.
BTW, I also simplified your pattern slightly by removing the escapes for ]
. Only the opening [
needs to be escaped.