Chris Schiffhauer
Chris Schiffhauer

Reputation: 17310

Regex.Replace with matched string in the replacement

I would like to compactly insert a <br /> tag before every line break in a string with regular expressions in C#. Can this be done? Currently, I am only able to replace the line break with the following:

myString = Regex.Replace(myString, @"\r\n?|\n", "<br />");

Can I modify this to include the matched text (i.e. either \r\n, \r, or \n) in the replacement?

Clearly, it can be done with a separate Match variable, but I'm curious if it can be done in one line.

Upvotes: 1

Views: 343

Answers (3)

Martin Ender
Martin Ender

Reputation: 44289

MSDN has a separate page just for .NET's regex substitution magic.

While the others are correct that the most general approach is to capture something and write back the captured contents with $n (where n is the captured group number), in your case you can simply write back the entire match with $&:

myString = Regex.Replace(myString, @"\r\n?|\n", "<br />$&");

If you are doing this a lot then avoiding the capturing could be a bit more efficient.

Upvotes: 2

Jon
Jon

Reputation: 437904

You can do this with a substitution in your "replace" string:

Regex.Replace(myString, @"(\r\n?|\n)", "$1<br />");

Upvotes: 1

Guffa
Guffa

Reputation: 700910

Use parentheses to capture the line break, and use $1 to use what you captured in the replace:

myString = Regex.Replace(myString, @"(\r\n?|\n)", "<br />$1");

Upvotes: 4

Related Questions