1

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.

Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88

3 Answers3

4

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");
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 2
    no need to capture anything. just use `$&` to write back the entire match. also the OP wanted to insert the tag *before* the line break ;) – Martin Ender Jun 14 '13 at 22:26
  • @m.buettner: Yes, for this specific use you could get everything matched instead of capturing. Thanks for pointing out that the tag was requested to go first, I updated the code. – Guffa Jun 14 '13 at 22:32
2

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.

Martin Ender
  • 43,427
  • 11
  • 90
  • 130
1

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

Regex.Replace(myString, @"(\r\n?|\n)", "$1<br />");
Jon
  • 428,835
  • 81
  • 738
  • 806