0

I am working on a Regex but its not working fine. My requirement is I have a string value and it has '##Anything##' tags like this. I want to replace this ##Anything## with a asp control

##name## donates a texbox ##Field## donates a combobox and so on

Syed Umar Ahmed
  • 5,612
  • 1
  • 21
  • 23

3 Answers3

3

The String.Replace approach should work fine and may be the best solution for you. But if you still want a regex solution, you could use something like this:

private const string REGEX_TOKEN_FINDER = @"##([^\s#]+)##"
private const int REGEX_GRP_KEY_NAME = 1;

public static string Format(string format, Dictionary<string, string> args) {
    return Regex.Replace(format, REGEX_TOKEN_FINDER, match => FormatMatchEvaluator(match, args));
}

private static string FormatMatchEvaluator(Match m, Dictionary<string, string> lookup) {
    string key = m.Groups[REGEX_GRP_KEY_NAME].Value;
    if (!lookup.ContainsKey(key)) {
        return m.Value;
    }
    return lookup[key];
}

It works on tokens such as this: ##hello##. The value between the ## are searched for in the dictionary that you provide, remember that the the search in the dictionary is case sensitive. If it is not found in the dictionary, the token is left unchanged in the string. The following code can be used to test it out:

var d = new Dictionary<string, string>();
d.Add("VALUE1", "1111");
d.Add("VALUE2", "2222");
d.Add("VALUE3", "3333");

string testInput = "This is value1: ##VALUE1##. Here is value2: ##VALUE2##. Some fake markers here ##valueFake, here ##VALUE4## and here ####. And finally value3: ##VALUE3##?";

Console.WriteLine(Format(testInput, d));
Console.ReadKey();

Running it will give the following output:

This is value1: 1111. Here is value2: 2222. Some fake markers here ##valueFake, here ##VALUE4## and here ####. And finally value3: 3333?

Francis Gagnon
  • 3,545
  • 1
  • 16
  • 25
1

You can do it using String.Replace() method:

//Example Html content
string html ="<html> <body> ##Name## </body> </html>";

 //replace all the tags for AspTextbox as store the result Html
string ResultHtml = html.Replace("##Name##","<asp:Textbox id=\"txt\" Text=\"MyText\" />");
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82
0

Again, the best hint is to use string.Replace(), perhaps in combination with string.Substring().

icbytes
  • 1,831
  • 1
  • 17
  • 27