[英]Create all combinations from regex
我有一些句子定義了隨機組合的模板:
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']
。
我該如何更改正則表達式?
(我今天想吃)* |(第二天)
正則表達式將選擇您想要的文本...
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]]
使用以下代碼,您將獲得類似
> 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)'
您可以進行額外的圓頂處理以消除多余的括號,這應該很容易
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.