首页 > 解决方案 > 正则表达式 ”?!” 有变量

问题描述

我正在测试用于互联网爬行的代码。

def getExternalLinks(bs, excludeUrl):
   externalLinks = []
   #Finds all links that start with "http" that do
   #not contain the current URL
   for link in bs.find_all('a',
      href=re.compile('^(http|www)((?!'+excludeUrl+').)*$')):
      if link.attrs['href'] is not None:
         if link.attrs['href'] not in externalLinks:
            externalLinks.append(link.attrs['href'])
   return externalLinks

我无法分析re.compile('^(http|www)((?!'+excludeUrl+').)*$')) 中的正则表达式((?!'+excludeUrl+'). )

标签: regex

解决方案


检查文档

(?!...)
如果 ... 下一个不匹配,则匹配。这是一个否定的前瞻断言。例如,Isaac (?!Asimov) 将匹配 'Isaac ' 仅当它后面没有 'Asimov' 时。


推荐阅读