Replace text matching a pattern in C#


Replace text matching a pattern

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in regular expressions, strings and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *