具有条件lookbehind的python正则表达式

时间:2012-12-21 06:41:02

标签: python regex lookbehind

我正在寻找以@开头并以第一个\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')

2 个答案:

答案 0 :(得分:2)

如果您愿意不使用reg expr,可以尝试:

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

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

答案 1 :(得分:0)

您的捕获组未捕获您正在寻找的文本:

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

现在,它有效:

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