import re
input = '''This is a hex number 0xAF67E49
This is NOT a hex number tgey736zde
This hex number 0xb34df49a appears in the middle of a sentence
This could be a hex number but has no letters 3689320'''
matches1 = re.findall('([0-9a-fA-F]{4,})', input)
matches2 = re.findall('0x([0-9a-fA-F]{4,})', input)
matches3 = re.findall('(0x[0-9a-fA-F]{4,})', input)
print('matches1: %s' % (str(matches1)))
print('matches2: %s' % (str(matches2)))
print('matches3: %s' % (str(matches3)))
老实说,有时候我认为在提问时最好包括一些实际的输入(或接近它的东西)和期望的输出。对于您的十六进制数,我想知道您是想捕获该值前面的0x还是避免它;第二个带有正则表达式原型的可变长度十六进制(稍微更正)将捕获诸如“def”、“bad”等内容。无论如何,拥有输入和所需输出有助于理解问题。回答问题的人也是如此。在
也就是说,对于你的第一个regex(因为我不明白你第二个想要什么),我倾向于使用“findall”,因为它更直接,并且产生组匹配,所以使用下面的输入(假设您知道我正在创建一个字符串来代替使用文件.read()方法,并使我的正则表达式捕获超过4个字符的字符串)
编码
输出
^{pr2}$说明
额外信息
为了使其更有效,您可能还需要研究如何使用lookaheads
相关问题 更多 >
编程相关推荐