In my code I find all matches elements and replace it with special values.
Regex imgRule = new Regex("img id=\\\".+?\\\"");
MatchCollection matches = imgRule.Matches(content.Value);
string result = null;
foreach (Match match in matches)
result = match.Value;
if (result != null)
{
var firstOrDefault = node.ListImages.FirstOrDefault();
if (firstOrDefault != null)
{
var htmlWithImages = content.Value.Replace(result, string.Format("img src='{0}' class='newsimage' width='300'", firstOrDefault.ImageUrlId));
node.Content = htmlWithImages;
}
}
But, my code is wrong because if there is more than one match it replace only the last one, how can I correct my code for replace all matches in text?
You are missing curly braces around the body of your for loop. Without the curly braces the only line that gets executed multiple times is the first one.
Try this instead:
I would also like to add two further points:
Regex.Replacethat you can use instead of first finding the strings you want to replace using a regex, and then usingstring.Replace.