简体   繁体   English

从字符串中提取十六进制数

[英]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 . 例如,字符串为: OxDB52 Message 1 of orderid 1504505254 for number +447123456789 rejected by Operator I want to extract hexadecimal OxDB52 part. 我想提取十六进制OxDB52部分。 I know it can be done checking for 0x in string. 我知道可以在字符串中检查0x

But is there any cool pythonic way to extract hexadecimal number from string? 但是有没有很酷的pythonic方法从字符串中提取十六进制数?

You can use regex pattern with re.findall() method: 您可以使用re.findall()方法使用正则表达式模式:

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 . 这将为您提供your_string中所有十六进制数字的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')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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