查找由已知字符串分隔的表达式

时间:2013-07-29 21:53:05

标签: python regex python-3.x

我希望列出表达式“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)

它返回一个空列表......欢迎任何帮助。

2 个答案:

答案 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]