salm
salm

Reputation: 1

VB.NET, I can't convert Unicode escape sequences to text

I watched many videos on YouTube, read many solutions on Google and Stack Overflow! Can anyone tell me how I can convert Unicode escape sequences to text?

I tried this:

Dim f = System.Net.WebUtility.HtmlDecode("sa3444444d4ds\u0040outllok.com")
MsgBox(f) 

and this:

Dim f = System.Uri.UnescapeDataString("sa3444444d4ds\u0040outllok.com")
MsgBox(f)

and this:

Dim myBytes As Byte() = System.Text.Encoding.Unicode.GetBytes("sa3444444d4ds\u0040outllok.com")

Dim myChars As Char() = System.Text.Encoding.Unicode.GetChars(myBytes)
Dim myString As String = New String(myChars)
MsgBox(myString)

and this:

    Dim f = UnicodeToAscii("sa3444444d4ds\u0040outllok.com")

    MsgBox(f)

Public Function UnicodeToAscii(ByVal unicodeString As String) As String

    Dim ascii As Encoding = Encoding.ASCII
    Dim unicode As Encoding = Encoding.Unicode
    ' Convert the string into a byte array. 
    Dim unicodeBytes As Byte() = unicode.GetBytes(unicodeString)

    ' Perform the conversion from one encoding to the other. 
    Dim asciiBytes As Byte() = Encoding.Convert(unicode, ascii, unicodeBytes)

    ' Convert the new byte array into a char array and then into a string. 
    Dim asciiChars(ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length) - 1) As Char
    ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0)
    Dim asciiString As New String(asciiChars)
    Return asciiString
End Function

Upvotes: 0

Views: 1081

Answers (1)

Andrew Morton
Andrew Morton

Reputation: 25013

You can use Regex.Unescape.

For example,

Dim s = "sa3444444d4ds\u0040outllok.com"
Console.WriteLine(Regex.Unescape(s))

outputs:

[email protected]

Credit to Tim Patrick for showing this in the Visual Studio Magazine article Overcoming Escape Sequence Envy in Visual Basic and C#.

Upvotes: 2

Related Questions