2016-01-26 177 views
1

我想要一個正則表達式停止在某個字符或行尾。我目前有:字符串到字符或行末的Python正則表達式

x = re.findall(r'Food: (.*)\|', text) 

它選擇「食物:」和「|」之間的任何東西。對於加入該行的結束,我想:

x = re.findall(r'Food: (.*)\||$', text) 

但這將返回空,如果文本是「食品:是偉大的」。我如何使這個正則表達式停在「|」或行結束?

回答

2

可以使用基於正則表達式的否定其[^|]*意味着什麼,但pipe

>>> re.findall(r'Food: ([^|]*)', 'Food: is great|foo') 
['is great'] 
>>> re.findall(r'Food: ([^|]*)', 'Food: is great') 
['is great'] 
+0

'打印re.findall(r'Food:(*)( ?:\ || $)','Food:is great | foo')'print' ['is great | foo']' –

+0

這適用於行尾,但在「|」之前停止失敗。例如,如果我有:「食物:很好|你好」,它會返回「很好|你好」,而不是「很好」 –

+0

檢查更新的答案,它將適用於這兩種情況。 – anubhava

0

一個更簡單的替代解決方案:

def text_selector(string) 
    remove_pipe = string.split('|')[0] 
    remove_food_prefix = remove_pipe.split(':')[1].strip() 
    return remove_food_prefix 
相關問題