Saturday, August 05, 2006

Replacing Tokenized String Using Regular Expression In .NET

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
static void Main(string[] args)
{
string text = "Contact name:$NAME$, address:$ADDRESS$, phone:$PHONE$, email:$EMAIL$...";
Dictionary<string, string> tokenDictionaries = new Dictionary<string, string>();
tokenDictionaries.Add("NAME", "Rob");
tokenDictionaries.Add("PHONE", "123456789");
tokenDictionaries.Add("EMAIL", "Rob@abc.com");
Console.WriteLine(ReplaceToken(text, tokenDictionaries));
Console.Read();
}

public static string ReplaceToken(string text, Dictionary<string, string> tokenDictionaries)
{
string pattern = @"\$.*?\$";
Match mc = Regex.Match(text, pattern);
if (mc.Success)
{
while (mc.Success)
{
if (!string.IsNullOrEmpty(mc.Value))
{
string tokenName = mc.Value.Substring(1, mc.Length - 2);
string tokenValue = string.Empty;
if (!string.IsNullOrEmpty(tokenName) && tokenDictionaries.ContainsKey(tokenName))
tokenValue = tokenDictionaries[tokenName];
text = text.Substring(0, mc.Index) + tokenValue + text.Substring(mc.Index + mc.Length);
mc = Regex.Match(text, pattern);
}
}
}
return text;
}
}
Result:
Contact name:Rob, address:, phone:123456789, email:Rob@abc.com...