【问题标题】:Regular Expression search in python if condition如果条件,python中的正则表达式搜索
【发布时间】:2015-12-01 05:11:42
【问题描述】:

我正在尝试在链接中搜索整个单词 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))

【问题讨论】:

  • 对不起,我的意思是正则表达式
  • 我不清楚这里有什么问题。您能否明确说明您遇到问题的代码部分,具体来说是它现在的行为方式以及您希望它的行为方式?
  • 我认为这可能与test string for a substring重复
  • 哪些示例输入不起作用?你怎么知道那个样本输入不起作用?如果它工作正常,它会输出什么?
  • 如果 'pid' 它可以识别所有的 pid 以及 sid 以及 id where,我只想将整个单词 'pid' 放入搜索中。

标签: python regex if-statement


【解决方案1】:

如果你的意思是你希望它匹配像/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:
    ...

【讨论】:

  • 实际上有三种情况,一种是 ?pid= ,一种是需要 sid=tyy,4mr&icmpid 而另一种只有 id 像 Widget 等。我只想显示第一个只有 ? pid
  • 谢谢我使用了这个表达式,它工作了 pattern = re.compile(r'(\?pid\=)')
  • 酷。但在这种情况下,您可能希望进行正确的 URL 解析。 Python 有一些库可以提供帮助:请参阅 urllib.parse (py3) 和 urlparse (py2)。可以轻松处理其他情况,例如 pid 参数不是第一个 (&amp;pid=...)。
猜你喜欢
  • 2015-02-23
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 2011-12-27
  • 2015-05-30
  • 2014-01-23
相关资源
最近更新 更多