Use regular expressions to replace text in a string in C#

The program creates a Regex object, passing its constructor a regular expression pattern that will identify text to replace. It calls the object's Replace method, passing it the replacement pattern.

private void btnGo_Click(object sender, EventArgs e)
{
Regex reg_exp = new Regex(txtPattern.Text);
lblResult.Text = reg_exp.Replace(
txtTestString.Text,
txtReplacementPattern.Text);
}

In this example, the search pattern is "[aeiouAEIOU]" and the replacement pattern is "." so the program replaces all instances of vowels with periods.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.