Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for hexadecimal and some other strings

My aim is to read a string and where ever find an integer or hexadecimal number, replace that with "[0-9]" My string is:

a = hello word 123 with the 0x54673ef75e1a
a1 = hello word 123 with the 0xf
a2 = hello word 123 with the 0xea21f
a3 = hello word 123 with the 0xfa

Have tried with following:

b = re.sub(r"(\d+[A-Fa-f]*\d+[A-Fa-f]*)|(\d+)","[0-9]",a)

Get the following output:

hello word [0-9] with the [0-9]x[0-9]a
hello word [0-9] with the [0-9]xf
hello word [0-9] with the [0-9]xea[0-9]
hello word [0-9] with the [0-9]xfa

But the output should be like that:

hello word [0-9] with the [0-9]
hello word [0-9] with the [0-9]
hello word [0-9] with the [0-9]
hello word [0-9] with the [0-9]
like image 726
Surya Gupta Avatar asked Nov 03 '22 08:11

Surya Gupta


2 Answers

Your pattern should be something like

b = re.sub(r"(0x[a-fA-F0-9]+|\d+)","[0-9]",a)

to distinguish between hex and decimal values.

like image 73
Dio F Avatar answered Nov 12 '22 18:11

Dio F


Use

re.sub(r"(0x[\da-fA-F]+)|(\d+)","[0-9]",a)

See http://ideone.com/nMMNJm

like image 40
irrelephant Avatar answered Nov 12 '22 17:11

irrelephant