2

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

Example input: MainDir[0x2f]SubDir[0x2f]Hello[0x2d]world[0x2e]txt

Desired output: MainDir/SubDir/Hello-world.txt

While I was posting this question I tried few options and came up with one possible answer and thought to post it for others. Please feel free to post if you have better options.

2 Answers 2

2

Short solution:

import re
s = "MainDir[0x2f]SubDir[0x2f]Hello[0x2d]world[0x2e]txt"
result = re.sub(r'\[0x[0-9a-f]{2}\]', lambda m: chr(int(m.group()[1:-1], 16)), s)

print(result)   # MainDir/SubDir/Hello-world.txt

\[0x[0-9a-f]{2}\] - matches hex string

1
  • Thanks and +1. Yes, lambda does shorten the code and I like the explicit check for 2 char hex string. Commented Mar 27, 2017 at 16:28
0

Here is how I ended up doing it:

def replHexWithascii(matchobj):
    #matchobj.group(0) contains [0xdd]
    #matchobj.group(0)[1:-1] gives strips off [ and ] and returns 0xdd
    #int(hexstring, 16) converts the hexstring '0x2f' to 47
    #chr(i) returns equivalent ascii
    hexstring = matchobj.group(0)[1:-1]
    return chr(int(hexstring, 16))

re.sub(r"\[.*?\]", replHexWithascii,"MainDir[0x2f]SubDir[0x2f]Hello[0x2d]world[0x2e]txt")

output:'MainDir/SubDir/Hello-world.txt'

References: re.sub

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.