十六进制和其他一些字符串的正则表达式

时间:2012-12-19 07:48:08

标签: python regex python-2.6

我的目标是读取一个字符串,并找到一个整数或十六进制数字,用“[0-9]”替换它 我的字符串是:

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

尝试了以下内容:

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

获取以下输出:

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

但输出应该是这样的:

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]

2 个答案:

答案 0 :(得分:1)

你的模式应该是

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

区分十六进制和十进制值。

答案 1 :(得分:1)

使用

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

请参阅http://ideone.com/nMMNJm