import re
mysentence = 'have a dog a cute cat and a big cow '
myanimal = 'dog', 'cat' , 'cow'
print re.finditer('have(.*?)myanimal',mysentence)
这不起作用,因为我没有采取动物串。有什么想让它发挥作用吗?
答案 0 :(得分:1)
Q>我的动物串不被采取
由于你在引号中有myanimal('have(。*?)myanimal'),它将被视为字符串的一部分,它的实际值不会被替换。
需要形成一个正则表达式,因为myanimal是list:
for animal in myanimal:
regex = re.compile('have a .*%s'%animal)
for m in re.finditer(regex, mysentence):
print m.group()
output:
have a dog
have a dog a cute cat
have a dog a cute cat and a big cow
这可能会有所帮助......
答案 1 :(得分:1)
>>> import re
>>> mysentence = 'have a dog a cute cat and a big cow '
>>> myanimal = 'dog', 'cat' , 'cow'
>>> m = re.match(r'have a (?:%s)' % '|'.join(map(re.escape, myanimal)), mysentence)
>>> m.group()
'have a dog'