【问题标题】:Python Regex findall But Not Including the conditional stringPython Regex findall 但不包括条件字符串
【发布时间】:2016-09-13 03:40:09
【问题描述】:

我有这个字符串:

The quick red fox jumped over the lazy brown dog lazy

我写了这个正则表达式,它给了我这个:

s = The quick red fox jumped over the lazy brown dog lazy

re.findall(r'[\s\w\S]*?(?=lazy)', ss)

这给了我以下输出:

['The quick red fox jumped over the ', '', 'azy brown dog ', '']

但我试图得到这样的输出:

['The quick red fox jumped over the ']

这意味着正则表达式应该给我一切,直到它遇到第一个 lazy 而不是最后一个,我只想使用 findall

【问题讨论】:

    标签: python regex findall


    【解决方案1】:

    通过添加? 使模式非贪婪

    >>> m = re.search(r'[\s\w\S]*?(?=lazy)', s)
    #                            ^
    >>> m.group()
    'The quick red fox jumped over the '
    

    【讨论】:

    • 我想使用findall。你能建议如何根据findall 写这个吗
    • @nikunj2512 re.findall(r'[\s\w\S]*?(?=lazy)', s)[0]
    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2012-10-19
    • 2022-08-19
    • 2012-06-25
    • 2016-04-03
    • 1970-01-01
    相关资源
    最近更新 更多