简体   繁体   中英

Extract hexadecimal number from string

I want to extract hexadecimal number from a string. For example, the string is: OxDB52 Message 1 of orderid 1504505254 for number +447123456789 rejected by Operator . I want to extract hexadecimal OxDB52 part. I know it can be done checking for 0x in string.

But is there any cool pythonic way to extract hexadecimal number from string?

You can use regex pattern with re.findall() method:

re.findall(r'0x[0-9A-F]+', your_string, re.I)

this will give you a list of all the hexadecimal numbers in your_string .

Demo:

>>> s = '0xDB52 Message 0x124A orderid 1504505254 for number 0xae45'
>>> re.findall(r'0x[0-9A-F]+', s, re.I)
['0xDB52', '0x124A', '0xae45']

假设单词被正确分开

[x for x in my_string.split() if x.startswith('0x')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM