Home > Blockchain >  Replace all hex encoding in string with equivalent ASCII value
Replace all hex encoding in string with equivalent ASCII value

Time:07-21

I have a string that contains hex values inside brackets []. I need to find all those strings and replace them with the decoded values (ASCII).

Example input: Help[2f]me[2f]with[2d]this[2e]question

Desired output: Help/me/with-this.question

I have used regex expression but could not find the right way to convert to ASCII by itself. The input value is dependent on a textbox and it will have multiple []s in the string, so the following code that I wrote does not work because the input character has to be the ASCII of hex inside [].

Dim input As String = "Hello[2f]world"
Dim replacement As String = "/"
Dim expression As String = "\[(.*?)\]"
Dim result As String = Regex.Replace(input, expression, replacement)

MsgBox(result)

CodePudding user response:

With Regex.Replace, you can use an "match evaluator function" for the replacement:

Imports System.Text.RegularExpressions

Module Module1

    Public Function HexToChar(m As Match) As Char
        Return Convert.ToChar(System.Convert.ToUInt32(m.Value.Trim("[]".ToCharArray()), 16))
    End Function

    Sub Main()
        Dim input As String = "Hello[2f]world[41][42][43]"
        Dim expression As String = "\[.*?\]"
        Dim evaluator As MatchEvaluator = AddressOf HexToChar
        Dim result As String = Regex.Replace(input, expression, evaluator)

        Console.WriteLine(result)

        Console.ReadLine()

    End Sub

End Module

Outputs:

Hello/worldABC

If you really want to, you can in-line the function:

Dim result = Regex.Replace(input, expression, Function(m)
                                                  Return Convert.ToChar(
                                                      System.Convert.ToUInt32(
                                                          m.Value.Trim({"["c, "]"c}), 16
                                                      )
                                                  )
                                              End Function)

References:

  • Related