2017-06-03 163 views
0

我有一個定義的模板隨意組合的句子的所有組合:創建一個從正則表達式

I like dogs/cats  
I want to eat today/(the next day) 

我試圖用一個正則表達式:

m = re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+)+)', sentence) 
words = m.group('list').split('/') 
combs = [comb for comb in [sentence.replace(m.group('list'), w) for w in words]] 

對於第一句話我得到['i like dogs', 'i like cats']這是我想。對於第二句,re.search返回None。我想得到的是['I want to eat today', 'I want to eat the next day']

我該如何改變正則表達式?

回答

0

(我想今天吃)* |(第二天)

是將選擇你想要的文字,正則表達式...

+0

號今天吃飯/(第二天)'我想創造兩個句子:'''我今天想吃','我想第二天吃']'。因此,我需要找到「今天」和「第二天」。 – user1406177

+0

使用此工具https://regex101.com/希望我在開始時擁有它。我發現編寫完美正則表達式的最好方法就是使用這個工具...你會很快拿起正則表達式。將你要搜索的文本粘貼到最大的盒子中,然後在上面的小方框中寫上你的「正則表達式」。自動文本將根據您的正則表達式突出顯示。在右下角你可以閱讀定義,右上角告訴你爲什麼選擇了東西。 –

0

r'(?P<list>[A-Za-z]+/([a-zA-Z]+|\(.+?\)))''

([a-zA-Z]+|\(.+?\))匹配的字符串,如「字「或」(某個詞)「。它也匹配「()」,我們需要使用strip刪除標題「(」和尾隨「)」。

m = re.search(r'(?P<list>[A-Za-z]+/([a-zA-Z]+|\(.+?\)))', sentence) 
words = m.group('list').split('/') 
combs = [comb for comb in [sentence.replace(m.group('list'), w.strip('()')) for w in words]] 
0

有了下面的代碼,你會得到類似

> sentence = 'I want to eat today/(the next day)' m = 
> re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+|(\(.*?\))))', sentence) 
> print m.group('list') words = m.group('list').split('/') combs = [comb 
> for comb in [sentence.replace(m.group('list'), w) for w in words]] 
> print combs 

['I want to eat today', 'I want to eat (the next day)' 

你可以圓頂額外的處理,以擺脫額外的括號應該是很容易從給定模板`我想