Reputation: 119
Check the code bellow. I want to replace all matching text [img=15]
with real image tag from text. I already created method called ReplaceMatching()
but problem is that this only can replace first matching not for all matching within text. Anyone can help me to implement loop on this method so it will replace all of matching?
C#:
public static void Main()
{
string text = "abcdef[img=15]ghijklmnop[img=16]qrstuvwxyz";
string foo = ReplaceMatching(text,"[img=","<img src=''>");
Console.WriteLine(foo);
}
private static string ReplaceMatching(string Source, string Find, string Replace)
{
int Place = Source.IndexOf(Find);
string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
return result;
}
Test link: https://dotnetfiddle.net/Mstl95
Note: the number after <img src= is dynamic its a image unique id. I have to replace it within method so i didnt used whole character to find
Upvotes: 0
Views: 90
Reputation: 270
Maybe this is what you are looking for, If I understood your question correctly. I know Regex is a pain, but its much better than using a naive approach (scanning the string with a foreach). This is a Regex Lazy Search, with group capture. The group is the content inside the parenthesis, that group will be replaced by the $1. If you need more groups, just put them between parenthesis and add $2, $3, etc. .*? means: .=everything. *=any number of repetition. ?=shortest match possible (to avoid getting a match it until the end of the next match):
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string text = "abcdef[img=15]ghijklmnop[img=16]qrstuvwxyz";
string replaced = Regex.Replace(text,@"\[img=(.*?)\]","<img src='$1'>");
//result = Regex.Replace(input, pattern, replacement);
Console.WriteLine(replaced); // abcdef<img src='15'>ghijklmnop<img src='16'>qrstuvwxyz
}
}
Upvotes: 2
Reputation: 2078
You can use Regular Expressions for this. Example:
public class Program
{
public static void Main()
{
string text = "abcdef[img=15]ghijklmnop[img=16]qrstuvwxyz";
var regex = new Regex(@"\[img=(\d+)\]");
var foo = regex.Replace(text, "<img src='$1'>");
Console.WriteLine(foo);
}
}
https://dotnetfiddle.net/wiLzx8
Upvotes: 0