Use regular expressions to replace text in the lines 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)
{
try
{
Regex reg_exp = new Regex(txtPattern.Text);
lblResult.Text = reg_exp.Replace(
txtInput.Text,
txtReplacementPattern.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

The trick in this example lies in the search and replacement patterns. In this example, the search pattern is (?m)^([^,]*), ([^\r]*)\r?$. The pieces of this expression have the following meanings:

Part Meaningt
(?m) This is an option directive that indicates a multiline string. This makes the ^ and $ characters match the beginning and end of a line rather than the beginning and end of the string.
^ Match the beginning of a line.
([^,]*) Match any character other than comma any number of times. This part is enclosed in parentheses so it forms the first match group.
, (A comma followed by a space.) Match a comma followed by a space.
({^\r]*) Match any character except carriage return any number of times. This part is enclosed in parentheses so it forms the second match group. (In C# the carriage return isn't part of the end of the line.)
[\r]? Match a carriage return zero or one times.
$ Match the end of the line.

The replacement pattern is "$2 $1". This says to output whatever was matched in the second match group, a space, and then the first match group.

This example takes this text:

    Archer, Ann
Baker, Bob
Carter, Cindy
Deevers, Dan

And converts it into this:

    Ann Archer
Bob Baker
Cindy Carter
Dan Deevers

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

  • 10/19/2010 10:30 PM OperatorX wrote:
    Rod,

    First - Thank you for the excellent site with such interesting and useful examples!

    Second - After building this example, I was not able to produce the same results that you describe in the post.

    The last name (Deevers, Dan) is not followed by a carriage return so it does not match. I was able to match all four names (producing the result that you included in the post) with the following regex:

    (?m)^([^,]*), ([^\r]*)(\r?)$

    Anyway, thank you again for sharing your knowledge!

    X
    Reply to this
    1. 10/20/2010 8:17 AM Rod Stephens wrote:
      You're absolutely correct! I didn't notice the comma in the final line of output.

      I've updated the example to fix it. Thanks for pointing this out!
      Reply to this
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.