我正在尝试提取一个子字符串(在本例中为“危险区域案例”),但它返回一个错误:
>>> res = 'class=\\"market_listing_item_name\\" style=\\"color: #D2D2D2;\\">Danger Zone Case<\\/span>'
>>> item = re.search('market_listing_item_name\\.+?>(.+?)<', res).group(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
虽然当我在 https://regexr.com/ 进入展位时,我得到了一场比赛。我做错了什么?
答案 0 :(得分:3)
'market_listing_item_name\\.+?>(.+?)<'
中的反斜杠被视为特殊字符。要告诉 python 将它们视为文字字符,请使用原始字符串:r'market_listing_item_name\\.+?>(.+?)<'
。
一个很好的提示是在用 python 编写正则表达式时总是用那个 r 前缀字符串,它有助于避免很多麻烦:)