我希望列出表达式“cat_”和“dog”之间的元素列表 在一个看起来像这样的字符串中:
input=...snake_perrot_cat_expression dog...
output='expression'
我希望返回“表达式”。我试图使用正则表达式,但我缺乏了解如何正确编写它的经验......
identifi=[]
for line in file:
identi=re.findall(r'cat_.*?dog', line)
identifi.append(identi)
它返回一个空列表......欢迎任何帮助。
答案 0 :(得分:3)
在您要查找的模式周围加上括号:
indentifi.extend(re.findall(r'cat_(.*?)dog', line))
例如,
In [137]: import re
In [138]: line = '...snake_perrot_cat_expression dog...'
In [142]: re.findall(r'cat_(.*?)\s*dog', line)
Out[142]: ['expression']
(添加了\s*
,因此不会匹配尾随空格。)
答案 1 :(得分:0)
如果每行只有一只“cat”和“dog”,我可以建议不使用正则表达式的解决方案,而“cat”首先出现:
print inpu.split('cat_')[1].split('dog')[0]