首页 > 解决方案 > 如何使用 python regex 提取上下文的第一部分

问题描述

string='there is a article here, there will be some other article too'

字符串是我要的内容,'there is a article'就停在那里,不匹配最后的文章。

我用过there.+article,但它给了我完整的内容'there is a article here, there will be some other article。不,我不想要这个。

有我想要的: 'there is a article'

标签: pythonregex

解决方案


您可以使用?非贪婪匹配。

>>> string='there is a article here, there will be some other article too'
>>> import re
>>> re.match("there.+article", string)
<re.Match object; span=(0, 57), match='there is a article here, there will be some other>
>>> re.match("there.+?article", string)
<re.Match object; span=(0, 18), match='there is a article'>

推荐阅读