5

私の目的は文字列を読み取ることであり、整数または16進数が見つかった場合は、それを「[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]
4

2 に答える 2

1

使用する

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

http://ideone.com/nMMNJmを参照してください

于 2012-12-19T07:54:58.593 に答える
1

あなたのパターンは次のようなものでなければなりません

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

16 進値と 10 進値を区別します。

于 2012-12-19T07:52:53.153 に答える