正则表达式匹配所有反斜杠字符,除了新行,回车等

时间:2014-12-09 11:58:55

标签: regex vb.net

我正在寻找一个正则表达式来将所有反斜杠字符转换为双黑色字符,除了换行符,回车符等。

此功能:

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

使用此输入:

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

错误地,生成以下输出:

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

是否可以更改行str = str.Replace("\", "\\"),以便它不会改变换行符?

2 个答案:

答案 0 :(得分:3)

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

试试这个。这应该这样做

答案 1 :(得分:0)

感谢vks,我提出了这个解决方案:

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