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

标签 python regex if-statement

我试图在链接中搜索整个单词 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:
    ...

关于python - python中的正则表达式搜索if条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32408293/

相关文章:

python - Pandas df 到字典,其值作为从 df 列聚合的 python 列表

python - 在 python 数据框中旋转/解压时间序列数据

python selenium perfLoggingPrefs过滤

regex - 如何使用 perl 的正则表达式迭代多行字符串

c - 批处理文件 if 语句不适用于 cmd

python - 根据日期和列值重新索引 Pandas 数据框

c++ - 查找 C++ 项目中有多少个 goto

javascript - 页面加载时的随机图像

excel - IF函数与多个VLOOKUP

python - 从 pandas 的数据框列中搜索字符串模式