我有句子定义随机组合的模板:
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)
(我今天想吃)* |(第二天)
正则表达式会选择你想要的文字......
答案 1 :(得分:0)
r'(?P<list>[A-Za-z]+/([a-zA-Z]+|\(.+?\)))''
([a-zA-Z]+|\(.+?\))
匹配&#34; word&#34;等字符串或者&#34;(某些词)&#34;。它也匹配&#34;()&#34;,我们需要删除标题&#34;(&#34;和尾随&#34;)&#34;使用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]]
答案 2 :(得分: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)'
你可以进行额外的处理,以摆脱应该很容易的额外括号