簡體   English   中英

具有條件lookbehind的python正則表達式

[英]python regex with conditional lookbehind

我在尋找與子串開始@ ,並與第一結束\\s發生。 必須在字符串的開頭或空格之后使用@

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

結果@one, @two, @three@four

我最終得到了這個: ((?<=\\s)|(?<=^))@[^\\s]+在sublime文本2中工作正常,但在python中返回空字符串。

python代碼

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

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

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

這實際上應該快得多......

您的捕獲組未捕獲您正在尋找的文本:

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

現在,它有效:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM