python - 如何使用 python 正则表达式提取上下文的第一部分

标签 python regex

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

String是内容,我想要'有一篇文章',就到此为止,不要与最后的文章匹配。

我使用了there.+article,但它给了我完整的内容'这里有一篇文章,还有其他一些文章。不,我不想要这个。

这就是我想要的: '有一篇文章'

最佳答案

可以使用?进行非贪婪匹配。

>>> 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'>

关于python - 如何使用 python 正则表达式提取上下文的第一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57105231/

相关文章:

Python:类:调用同一个类中的函数

python - 属性子集的只读数据 View (不是副本)

java - 匹配字符串内的 URL

java - 如何解析字符串以从中获取双值

java - 如何匹配包括行终止符在内的任何符号?

python - 在python正则表达式中匹配多行

python - 如何将计算应用于文本文件的列?

python - "sample larger than population"in random.sample python

Javascript匹配并替换以下符号

php - 使用 preg_replace 缩小 CSS