Title: Replace text matching a pattern in C#
This example uses the following code to replace text matching a pattern within a string.
// Make the replacements.
private void btnGo_Click(object sender, EventArgs e)
{
Regex reg_exp = new Regex(txtPattern.Text);
lblResult.Text = reg_exp.Replace(
txtTestString.Text,
txtReplacementPattern.Text);
}
This code creates a Regex object, passing its constructor a regular expression pattern that will identify the text to replace. It calls the object's Replace method, passing it the replacement pattern.
In this example, the search pattern is "[aeiouAEIOU]" and the replacement pattern is "." so the program replaces all instances of vowels with periods.
Download the example to experiment with it and to see additional details.
|