为什么会这样重复详细信息导致regex返回空?

2024-05-16 22:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串:

s = '<a class="biz-name"><span>Gus’s World Famous Fried Chicken</span></a>'

这将返回预期结果:

regex = re.compile('''<a class="biz-name[\w\W]*?<span>(.*?)</span>''')
regex.findall()
['Gus’s World Famous Fried Chicken']

但是返回空值:

regex = re.compile('''<a class="biz-name[\w\W]*?<span>(.*?)</span>''', re.VERBOSE)
regex.findall()
[]

唯一的区别是re.VERBOSE标志。你知道吗


Tags: 字符串namereworldverboseclassregexspan
1条回答
网友
1楼 · 发布于 2024-05-16 22:36:12

阅读the docs

Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like *?, (?: or (?P<...>.

问题是带有re.VERBOSEa class与匹配的aclass相同,这不在您的输入中。您需要转义空格(并使用原始字符串来保证一般的正确性):

re.compile(r'''<a\ class="biz-name[\w\W]*?<span>(.*?)</span>''', re.VERBOSE)
       raw ^     ^ escape space or it doesn't count in VERBOSE mode

相关问题 更多 >