bastos.sergio
bastos.sergio

Reputation: 6764

Regex to match all backslash characters, except new line, carriage return, etc

I'm looking for a regex to escape all backslash characters into double blackshash characters, except for newlines, carriage returns, etc..

This function:

Public Function EscapeInvalidCharacters(ByVal str As String) As String
    str = str.Replace("\", "\\")            ' Backslash

    str = str.Replace("'", "\'")            ' Single quote
    str = str.Replace("""", "\""")          ' Double quote
    str = str.Replace(vbNewLine, "\n")      ' New line
    str = str.Replace(vbCr, "\r")           ' Carriage return
    str = str.Replace(vbTab, "\t")          ' Horizontal tab
    str = str.Replace(vbBack, "\b")         ' Backspace
    str = str.Replace(vbFormFeed, "\f")     ' Form feed

    Return str
End Function

with this input:

"This is a test.\nThis is another test.\n"

Wrongly, generates the following output:

"This is a test.\\nThis is another test.\\n"

Is it possible to alter the line str = str.Replace("\", "\\") so that it doesn't alter the newlines?

Upvotes: 2

Views: 1319

Answers (2)

bastos.sergio
bastos.sergio

Reputation: 6764

Thanks to vks, I came up with this solution:

Public Function EscapeInvalidCharacters(ByVal str As String) As String
    'str = str.Replace("\", "\\")           ' Backslash
    str = Regex.Replace(str, "\\(?!n|r|t|b|f)", "\\")' Backslash

    str = str.Replace("'", "\'")            ' Single quote
    str = str.Replace("""", "\""")          ' Double quote
    str = str.Replace(vbNewLine, "\n")      ' New line
    str = str.Replace(vbCr, "\r")           ' Carriage return
    str = str.Replace(vbTab, "\t")          ' Horizontal tab
    str = str.Replace(vbBack, "\b")         ' Backspace
    str = str.Replace(vbFormFeed, "\f")     ' Form feed

    Return str
End Function

Upvotes: 0

vks
vks

Reputation: 67978

\(?!r|n|t|b|f)

Try this.This should do it

Upvotes: 4

Related Questions