Introduction
Hello. Let’s begin our conversation. They’re many cases when you have to use a text template. For example, you have a mail engine, which performs sending of letters to many users and you don’t want to create special letter for every user (let’s imagine that there are thousand). Your email must be something like that: ”Hello Mr. #username, your email #email is not valid any more. Please, contact to #admin to solve a problem”.
You see, that you have just a template and that letter can be send to any users after substitution user’s data. To perform that task using MS .NET Framework is very simple. To do that, we will use Regular Expressions.
Using the code
The input of our method of replacing (we will call it Parse) will be a string with the text. The result value is a string with transformed data. As the keys we will use notation like this: #any_text_or_numbers.
But before parsing we have to know what text should be replicated. For that goal we’ll use a hash table to store keys and their values. Before, describing the usage of regular expressions, let’s consider an algorithm of replacing keys.
copyfrom = lastindex+lastlenght;
copycount = m.Index - (lastindex+lastlenght);
result+=text.Substring(copyfrom, copycount )+GetHashData(m.Value);
lastindex = m.Index;
lastlenght = m.Length;
m = m.NextMatch();
Let’s back to Regular Expressions (RE). The RE which corresponds to : #any_text_or_numbers is @"#(\w)+"
.
Additional information on all symbols used in RE you will easily find in MSDN. Here is the code for the methods of replacing keys by their values.
public string Parse (string text)
{
string result = string.Empty;
string pat = @"#(\w)+";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(text);
int lastindex=0;
int lastlenght = 0;
int copyfrom=0;
int copycount = text.Length;
while (m.Success)
{
copyfrom = lastindex+lastlenght;
copycount = m.Index - (lastindex+lastlenght);
result+=text.Substring(copyfrom, copycount )
+GetHashData(m.Value);
lastindex = m.Index;
lastlenght = m.Length;
m = m.NextMatch();
}
if ((lastindex+lastlenght)<text.Length)
{
result+=text.Substring(lastindex+lastlenght,
text.Length-(lastindex+lastlenght) );
}
return result;
}
That’s it for now.