Skip to main content
 首页 » 编程设计

python之python中的正则表达式搜索if条件

2024年10月24日25webabcd

我试图在链接中搜索整个单词 pid,但在某种程度上这也在这段代码中搜索 id

    for a in self.soup.find_all(href=True): 
 
        if 'pid' in a['href']: 
            href = a['href'] 
            if not href or len(href) <= 1: 
                continue 
            elif 'javascript:' in href.lower(): 
                continue 
            else: 
                href = href.strip() 
            if href[0] == '/': 
                href = (domain_link + href).strip() 
            elif href[:4] == 'http': 
                href = href.strip() 
            elif href[0] != '/' and href[:4] != 'http': 
                href = ( domain_link + '/' + href ).strip() 
            if '#' in href: 
                indx = href.index('#') 
                href = href[:indx].strip() 
            if href in links: 
                continue 
 
            links.append(self.re_encode(href)) 

请您参考如下方法:

如果你的意思是你希望它匹配像/pid/0002这样的字符串而不是/rapid.html,那么你需要排除两边的单词字符.像这样的东西:

>>> re.search(r'\Wpid\W', '/pid/0002') 
<_sre.SRE_Match object; span=(0, 5), match='/pid/'> 
>>> re.search(r'\Wpid\W', '/rapid/123') 
None 

如果“pid”可能位于字符串的开头或结尾,您需要添加额外的条件:检查行的开头/结尾或非单词字符:

>>> re.search(r'(^|\W)pid($|\W)', 'pid/123') 
<_sre.SRE_Match object; span=(0, 4), match='pid/'> 

参见 the docs有关特殊字符的更多信息。

你可以这样使用它:

pattern = re.compile(r'(^|\W)pid($|\W)') 
if pattern.search(a['href']) is not None: 
    ...