Python 从正则表达式创建所有组合
我有一些句子定义了随机组合的模板:Python 从正则表达式创建所有组合,python,regex,Python,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'),
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]]
m=re.search(r'(?P[A-Za-z]+/([A-Za-z]+)+),句子)
words=m.group('list').split('/'))
combs=[comb for comb in[句子.替换(m.group('list'),w)for w in words]]
第一句话是我想要的。对于第二句话,re.search
返回None
。我想要的是[“我今天想吃”,“我第二天想吃”]
我需要如何更改正则表达式?(我今天想吃)*|(第二天)
是将选择所需文本的正则表达式…r'(?p[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]]
m=re.search(r'(?P[A-Za-z]+/([A-Za-z]+\(.+?\)),句子)
words=m.group('list').split('/'))
combs=[comb for comb in[句子.替换(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)'
我今天(第二天)想吃东西=
>检索(r'(?P[A-Za-z]+/([A-Za-z]+|(\(.*)))),句子)
>打印m.group('list')单词=m.group('list')。拆分('/')梳=[comb]
>对于comb in[句中,将(m.group('list'),w)替换为w in words]]
>印花梳子
[“我今天想吃”,“我(第二天)想吃”
你可以通过额外的处理来去除额外的括号,这应该很容易使用这个工具,希望我刚开始时就有了它。我发现编写完美正则表达式的最好方法是使用这个工具…你会很快找到正则表达式。粘贴你的“文本,在最大的框中搜索”,然后写“你的正则表达式”在上面的小框中。文本将根据您的正则表达式自动突出显示。右下角您可以阅读定义,右上角告诉您选择内容的原因。否。从给定模板
我想今天吃/(第二天)
我想创建两个句子:[“我想今天吃”,“我想第二天吃”]
。因此,我需要找到今天的和第二天的。