【问题标题】:python regex with conditional lookbehind带有条件后视的python正则表达式
【发布时间】:2012-12-21 06:41:01
【问题描述】:

我正在寻找以@ 开头并以第一个\s 结尾的子字符串。 @ 必须在字符串的开头或空格之后。

示例@one bla bla bla @two @three@four #@five

结果@one, @two, @three@four

我最终得到了这个回复:((?<=\s)|(?<=^))@[^\s]+,它在 sublime text 2 中运行良好,但在 python 中返回空字符串。

python 代码

re.findall(r'((?<=^)|(?<=\s))@[^\s]+', '@one bla bla bla @two @three@four #@five')

【问题讨论】:

  • 你是如何在 Python 中使用这个正则表达式的?
  • 您不需要在第一个分支中进行回顾。 ^ 已经是一个零宽度断言。

标签: python regex lookbehind


【解决方案1】:

如果你愿意不使用 reg expr 你可以试试:

>>> s ="@one bla bla bla @two @three@four #@five"
>>> filter(lambda x:x.startswith('@'), s.split())
['@one', '@two', '@three@four']

这实际上应该快得多...

【讨论】:

    【解决方案2】:

    您的捕获组没有捕获您真正需要的文本:

    (?:(?<=^)|(?<=\s))(@[^\s]+)
    

    现在,它可以工作了:

    >>> re.findall(r'(?:(?<=^)|(?<=\s))(@[^\s]+)', '@one bla bla bla @two @three@four #@five')
    ['@one', '@two', '@three@four']
    

    【讨论】:

    • 值得一提的是,这种行为的原因是如果存在捕获组,findall 会返回它们而不是返回整个匹配项(即使它确实返回如果没有组,则整场比赛)。这已记录在案,但似乎总是让人们感到惊讶。
    • @BrenBarn:嗯,我不知道。谢谢。
    猜你喜欢
    • 2021-09-02
    • 1970-01-01
    • 2016-12-23
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    相关资源
    最近更新 更多