Sunday, April 18, 2010

String replacement with Regular Expressions

I answered a question last week on a forum about using Regular Expressions for complex string replacements so I thought I might just post a small example. For simple string replacement there’s the String.Replace method, but whenever you need to manipulate the match you want to replace in order to build the replacement string, the RegEx.Replace method does the job. Here’s a small code sample that searches in a string for a parameter named “username” and its value and then builds a HTML link stirng with it.

private void button1_Click(object sender, EventArgs e)
{
 string s = "username=myusername";
 Regex patern = new Regex(@"\[(username=(\W+))\]");
 MatchEvaluator matchEval = new MatchEvaluator(GetReplacement);

 s = patern.Replace(s,GetReplacement);

 MessageBox.Show(s);

}
 
private string GetReplacement(Match m)
{
 return "" + m.Groups[2] + "";
} 

No comments:

Post a Comment