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 :)

Comments

  • Anonymous
    May 14, 2008
    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

  • Anonymous
    September 24, 2014
    Depends on the end-application: HTML needs [' & # 1 3 '] which does not render (but {space}'d prior to HTML5); Javascript alert('needs n as usual') [' n e e d s   n   a s  u s u a l ']. Ray.