2012-12-19 37 views
5

Mục đích của tôi là để đọc một chuỗi và có bao giờ tìm thấy một số nguyên hoặc số thập lục phân, thay thế mà với "[0-9]" chuỗi của tôi là:biểu hiện thường xuyên cho hệ thập lục phân và một số chuỗi khác

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 

đã thử với sau:

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

Lấy ra sau đây:

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 

Nhưng outpu t nên như thế:

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] 
+0

Hãy thử sử dụng 'r '(0x [A-Pháp-f \ d] + | \ d +)'' như regex. – Blender

Trả lời

1

mô hình của bạn nên được một cái gì đó giống như

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

để phân biệt giữa hex và giá trị thập phân.

+1

thnx làm việc của nó .. :) –

Các vấn đề liên quan