Skip to main content
 首页 » 编程设计

python之正则表达式量词

2025年05月04日35bluestorm

我是正则表达式的新手,这让我很困惑。

在下面的示例中,我想提取 facebook.com/pages/Dr-Morris-Westfried-Dermatologist/176363502456825?id=176363502456825&sk=info。我已经阅读了惰性量词和回顾,但我仍然无法拼凑出正确的正则表达式。我希望 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"> 

请您参考如下方法:

尽管我很喜欢正则表达式,但这是一个 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']