Simple Regex Replace() question.

S

Sin Jeong-hun

I'm trying to replace \n with @(representing the actual new line
character). Of course, \\n should not be replaced. What I'm trying to
do is simply what the good-old printf does.
For example, "\\n \n" should be converted to "\\n @". I used,
Regex r = new Regex(@"[^\\](\\n)");
textBox2.Text = r.Replace(textBox1.Text, "@");
But the result was "\\n@". It looks like one character before \n is
also treated as a character to be replaced. How can I fix this? Again,
the correct result is "\\n @".
Thank you.
 
A

Anthony Jones

Sin Jeong-hun said:
I'm trying to replace \n with @(representing the actual new line
character). Of course, \\n should not be replaced. What I'm trying to
do is simply what the good-old printf does.
For example, "\\n \n" should be converted to "\\n @". I used,
Regex r = new Regex(@"[^\\](\\n)");
textBox2.Text = r.Replace(textBox1.Text, "@");
But the result was "\\n@". It looks like one character before \n is
also treated as a character to be replaced. How can I fix this? Again,
the correct result is "\\n @".


The space in the input string is the character that matches [^\\] in the
pattern and is therefore part of the string which gets replaced.

Try:-

Regex r = new Regex(@"(?<!\\)\\n");

See:-

http://msdn2.microsoft.com/en-us/library/bs2twtah.aspx
 
S

Sin Jeong-hun

I'm trying to replace \n with @(representing the actual new line
character). Of course, \\n should not be replaced. What I'm trying to
do is simply what the good-old printf does.
For example, "\\n \n" should be converted to "\\n @". I used,
Regex r = new Regex(@"[^\\](\\n)");
textBox2.Text = r.Replace(textBox1.Text, "@");
But the result was "\\n@". It looks like one character before \n is
also treated as a character to be replaced. How can I fix this? Again,
the correct result is "\\n @".

The space in the input string is the character that matches [^\\] in the
pattern and is therefore part of the string which gets replaced.

Try:-

Regex r = new Regex(@"(?<!\\)\\n");

See:-

http://msdn2.microsoft.com/en-us/library/bs2twtah.aspx

Thanks a lot! Worked like a charm. And thanks for the link, too.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top