Welcome to MSDN Blogs Sign in | Join | Help

Replacing \n With \r using the Regex.Replace

 

Here is a question i received the other day from one of victims (Nick):

====

I've been watching the recordings of your webcasts on regex (just about to see no. 7) one query that I have is how to include metacharacters in the replacement string. So in a simple example I want to replace a linefeed with, for arguments sake, a carriage return.

if I do string myString1 = Regex.Replace(myString, "\n", "\r"); it finds the new line but it replaces it with a literal \r. The same holds true in Expresso.

After 25 years with Unix and vi I can do this so what am I missing in .Net ? Any help greatly appreciated.

====

 

There may be multiple ways to deal with this but the answer I came up with for this particular scenario was this:

 

String myString1 = Regex.Replace(myString,"\n",Convert.ToString(Convert.ToChar(13)));

 

It was a quick fix so, by all means, if you have a better or even cleaner way you think it could be written feel free to comment with your suggestion :)

Published Monday, May 12, 2008 7:40 PM by zainnab

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

Wednesday, May 14, 2008 10:02 PM by Mr. Jiggs

# re: Replacing \n With \r using the Regex.Replace

Imports System.Text.RegularExpressions

Public Class frmMain

   Const cr As String = vbCr

   Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

       TextBox1.Text = "Line  1" & vbNewLine & _

                       "Line  2" & vbNewLine & _

                       "Line  3" & vbNewLine & _

                       "Line  4" & vbNewLine & _

                       "Line  5" & vbNewLine & _

                       "Line  6" & vbNewLine & _

                       "Line  7" & vbNewLine & _

                       "Line  8" & vbNewLine & _

                       "Line  9" & vbNewLine & _

                       "Line 10" & vbNewLine & _

                       "Line 11" & vbNewLine

   End Sub

   Private Sub mnuFileGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFileGo.Click

       TextBox2.Text = Regex.Replace(TextBox1.Text, "\n", cr)

   End Sub

   Private Sub mnuFileExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFileExit.Click

       Application.Exit()

   End Sub

End Class

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker