正则表达式量词

2024-06-17 11:09:18 发布

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

我是regex新手,这让我很为难。在

在下面的示例中,我想提取facebook.com/pages/Dr-Morris-Westfried-Dermatologist/176363502456825?id=176363502456825&sk=info。我读了很多关于懒惰量词和lookbehind的文章,但是我仍然不能拼凑出正确的正则表达式。我希望facebook.com\/.*?sk=info能够工作,但它捕获的太多了。你们能帮忙吗?在

<i class="mrs fbProfileBylineIcon img sp_2p7iu7 sx_96df30"></i></span><span class="fbProfileBylineLabel"><span itemprop="address" itemscope="itemscope" itemtype="http://schema.org/PostalAddress"><a href="https://www.facebook.com/pages/Dr-Morris-Westfried-Dermatologist/176363502456825?sk=page_map" target="_self">7508 15th Avenue, Brooklyn, New York 11228</a></span></span></span><span class="fbProfileBylineFragment"><span class="fbProfileBylineIconContainer"><i class="mrs fbProfileBylineIcon img sp_2p7iu7 sx_9f18df"></i></span><span class="fbProfileBylineLabel"><span itemprop="telephone">(718) 837-9004</span></span></span></div></div></div><a class="title" href="https://www.facebook.com/pages/Dr-Morris-Westfried-Dermatologist/176363502456825?id=176363502456825&amp;sk=info" aria-label="About Dr. Morris Westfried - Dermatologist">

Tags: divinfocomidfacebookpagesclasssk
3条回答

为什么你的模式不起作用:

您的模式不起作用,因为regex引擎在字符串中从左到右尝试您的模式。在

当regex引擎遇到字符串中的第一个facebook.com\/时,并且由于在之后使用了.*?,regex引擎将向(可能的)匹配结果中添加所有字符(包括"或{}或空格),直到找到sk=info(因为{}可以匹配除换行符之外的任何字符)。在

这就是为什么fejese建议用[^"]替换点,或者alitemind建议用[^>]替换它,使模式在字符串(第一个)的这个位置失败。在

如果要处理html,使用html解析器是最简单的方法。但是,对于ponctual match或search/replace,请注意,如果html解析器提供了安全性和简单性,那么就性能而言,它是有代价的,因为您需要为单个任务加载文档的整个树。在

这是有效的:)

facebook\.com\/[^>]*?sk=info

Regular expression visualization

Debuggex Demo

只有.*时,它首先找到facebook.com,然后继续到sk=info。因为有另一个facebook.com之间,所以要重叠它们。在

你不想要的唯一的东西是一个>(或者<,在其他字符中),因此将任何字符改为除了>之外的任何内容都可以找到与sk=info最接近的facebook.com最接近sk=info。在

是的,对HTML使用regex应该只在基本任务中使用。否则,请使用解析器。在

尽管我非常喜欢regex,但这是一个html解析任务:

>>> from bs4 import BeautifulSoup
>>> html = .... # that whole text in the question
>>> soup = BeautifulSoup(html)
>>> pred = lambda tag: tag.attrs['href'].endswith('sk=info')
>>> [tag.attrs['href'] for tag in filter(pred, soup.find_all('a'))]
['https://www.facebook.com/pages/Dr-Morris-Westfried-Dermatologist/176363502456825?id=176363502456825&sk=info']

相关问题 更多 >