python - Re.findall 仅返回 Python 2.7 中的第一个匹配项

标签 python regex

my_file 中的句子以单词后跟数字开头(例如“City1”)时,andmy_file 中还有另一个句子> 以“City2”开头,以下代码仅返回第一句:

description = re.findall("\n"+i+"[\s\,\d\(].*\.\n", my_file) #i equals 'City'
if description:
        for d in description:
            d = d.replace('\n', ' ')
            bufferlist.append(d)
            bufferlist[:] = unique( bufferlist ) #unique is a function removing duplicates from a list while keeping its order
            my_string = ' '.join(bufferlist)
            del bufferlist[:]
else:
        my_string = '0'

为什么我无法同时获取 my_string 中的第一句和第二句?

编辑 问题或问题的一部分是 del bufferlist[:]。这防止了每次迭代中所需的匹配堆积。 bufferlist 必须在循环后删除。

最佳答案

(?:^|(?<=\n))City[\s\,\d\(].*\.(?=\n|$)

试试这个。您正在使用 \n,它可能不会留给其他人匹配。

查看演示。

https://regex101.com/r/VIXyar/1

关于python - Re.findall 仅返回 Python 2.7 中的第一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42396384/

相关文章:

python - Django 上的正则表达式不起作用

python - 检查文件中的重复项两次 - Python

javascript - Django模板: dynamic variable name in javascript

python - 在 Python 中,当您在函数内部导入时会发生什么?

python - 文件操作和优化python代码

regex - 用 php preg_replace 只替换一次字符串

regex - 跨多行的复杂匹配

python - 从带有冒号的行中解析单词(简单的初学者作业)

regex - % :s/\([0-9]*\)_\(*\)/\2 will not rename files

java - 获取字符串中的字符串