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.

3 Answers 3

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");
Sign up to request clarification or add additional context in comments.

2 Comments

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 ;)
@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.
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.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.