regular expressions use

M

max(01)*

hi everyone.

i would like to do some uri-decoding, which means to translate patterns
like "%2b/dhg-%3b %7E" into "+/dhg-; ~": in practice, if a sequence like
"%2b" is found, it should be translated into one character whose hex
ascii code is 2b.

i did this:

....
import re
import sys

modello = re.compile("%([0-9a-f][0-9a-f])", re.IGNORECASE)

def funzione(corrispondenza):
return chr(eval('0x' + corrispondenza.group(1)))

for riga in sys.stdin:
riga = modello.sub(funzione, riga)
sys.stdout.write(riga)
....

please comment it. can it be made easily or more compactly? i am a
python regexp novice.

bye

max

ps: i was trying to pythonate this kind of perl code:

$riga =~ s/%([A-Fa-f0-9][A-Fa-f0-9])/chr(hex($1))/ge;
 
P

Peter Otten

max(01)* said:
would like to do some uri-decoding, which means to translate patterns
like "%2b/dhg-%3b %7E" into "+/dhg-; ~": in practice, if a sequence like
"%2b" is found, it should be translated into one character whose hex
ascii code is 2b.

i did this:

...
import re
import sys

modello = re.compile("%([0-9a-f][0-9a-f])", re.IGNORECASE)

def funzione(corrispondenza):
return chr(eval('0x' + corrispondenza.group(1)))

You can specify the base for str to int conversion, e. g:

return chr(int(corrispondenza.group(1), 16))

And then there is also urllib.unquote() in the library.

Peter
 
P

Paul McGuire

Perhaps a bit more verbose than your Perl regexp, here is a decoder
using pyparsing.

-- Paul

# download pyparsing at http://pyparsing.sourceforge.net
from pyparsing import Word,Combine

# define grammar for matching encoded characters
hexnums = "0123456789ABCDEFabcdef"
encodedChar = Combine( "%" + Word(hexnums,exact=2) )

# define and attach conversion action
def unencode(s,l,toks):
return chr(int(toks[0][1:],16))
encodedChar.setParseAction( unencode )

# transform test string
data = "%2b/dhg-%3b %7E"
print encodedChar.transformString( data )
"""
Prints "+/dhg-; ~":
"""
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,234
Latest member
SkyeWeems

Latest Threads

Top