使用re-library python无法正确分析结束行

2024-06-30 15:53:37 发布

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

考虑字符串:

<p class="sm clg" data-rlocation="Uttam Nagar East">Uttam Nagar East, Delhi <span class="to-txt" id="citytt1">B-24, East Uttam Nagar, Uttam Nagar East,<br>Delhi<span> - </span>110059

我想用regex函数得到结果Uttam Nagar East,但得到的结果是

Uttam Nagar East">Uttam Nagar East, Delhi <span class="to-txt" id="citytt1'

我试过用

print(re.findall(r'data-rlocation="(.*)["]',contents))

以及

print(re.findall(r'data-rlocation="(.*)"',contents))

Tags: toretxtiddataclassspanprint
3条回答

(.*)在其捕获中包含右引号。请尝试以下操作:

>>> re.findall(r'data-rlocation="([^"]*)"', contents)
['Uttam Nagar East']

看看它是如何工作的here。你知道吗

默认情况下,*是贪婪的,这意味着它试图使用尽可能多的字符。如果希望匹配尽可能少的字符,可以使用非贪婪限定符*?

print(re.findall(r'data-rlocation="(.*?)"',contents))

更多信息:https://docs.python.org/3.5/howto/regex.html#greedy-versus-non-greedy

你正在使用贪婪的正则表达式,你可以加上“?”使它不贪婪

import re
contents = '<p class="sm clg" data-rlocation="Uttam Nagar East">Uttam Nagar East, Delhi <span class="to-txt" id="citytt1">B-24, East Uttam Nagar, Uttam Nagar East,<br>Delhi<span> - </span>110059'
print(re.findall(r'data-rlocation="(.*?)"',contents))

相关问题 更多 >