Wednesday, October 9, 2013

.NET Regex - using $ and \r\n

Symptom:
I have a list of values in a textbox...

apple
banana
cherry
donut

In a textbox it looks like this:

TextBox1.Text = "apple\r\nbanana\r\ncherry\r\ndonut\r\n";

Let's parse through the list using a pattern and do a replace...

Then I'll do a replace...

TextBox1.Text = Regex.Replace(TextBox1.Text,  "^(.*)$" , "I like to put $1 on my plate.\r\n", RegexOptions.Multiline);

I would expect to see this:

I like to put apple on my plate.
I like to put banana on my plate.
I like to put cherry on my plate.
I like to put donut on my plate.

Instead, I see this:

I like to put apple
 on my plate.
I like to put banana
 on my plate.
I like to put cherry
 on my plate.
I like to put donut
 on my plate.

It turns out that $ is matching \n, but not \r.

Solution:

Change to this and it worked as expected:

TextBox1.Text = Regex.Replace(TextBox1.Text,  "^(.*)\r\n" , "I like to put $1 on my plate.\r\n", RegexOptions.Multiline);