繁体   English   中英

从正则表达式创建所有组合

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM