2012-12-21 100 views
0

我正在尋找以@開頭的子串,並以第一個\s的發生結束。 必須在字符串開頭或空格後有@python正則表達式有條件lookbehind

@one bla bla bla @two @[email protected] #@five

結果@one, @two, @[email protected]

我結束了這種重:((?<=\s)|(?<=^))@[^\s]+它工作在崇高的文本2罰款,但在Python返回空字符串。

Python代碼

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

你如何使用這個表達式在Python? – Blender

+0

你不需要在第一個分支倒序。 '^'已經是一個零寬度的斷言。 –

回答

0

你捕獲組不捕捉,你真正需要的文字:

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

現在,它的工作原理:

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

值得一提的是,這種行爲的原因是,如果捕獲組存在,'findall'會返回它們而不是返回整個匹配(即使它*在沒有組時返回整個匹配)。這是記錄,但它似乎總是讓人驚訝。 – BrenBarn

+0

@BrenBarn:呃,我不知道。謝謝。 – Blender

+0

是的。那工作。非常感謝 – qubblr

2

如果你願意不使用reg expr,你可以試試:

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

這實際上要快很多......

+0

太棒了!這個解決方案實際上工作速度快了2倍 – qubblr