[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Replace text in the lines of a string in C#

Replace text in the lines of a string

This example uses the following code to replace text in the lines of a string.

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); } }

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.

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

Part Meaning
(?m) This is an option directive that indicates a multi-line 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.
(.*) Match any character any number of times. This part is enclosed in parentheses so it forms the second match group.
\r Match a carriage return. (In C# this isn't part of the end of the line.)
$ 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

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.