You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用regex库从executada(s)起始文本提取多组CNPJ问题

问题原因

原有正则将executada(s):到最后一个CNPJ的整段内容作为单个匹配项,重复出现的捕获分组只会保留最后一次匹配的值,因此仅能输出第二个CNPJ结果。

解决方法

使用第三方regex库支持的可变长度正向后视断言,先校验当前匹配位置位于executada(s):之后,再逐个匹配符合格式的CNPJ,调整后代码如下:

import regex

text = """
Solicite-se ao BANCO CENTRAL, via protocolo digital - SISBACEN ,
o BLOQUEIO de créditos existentes até o limite de R$ 30.257,45 (trinta mil, duzentos e
cinquenta e sete reais e quarenta e cinco centavos) da(s) executada(s): J.HENRIQUE
GALVANI COMERCIO DE ROUPAS - ME - CNPJ 10.547.889/0001-85, Riane Confecções de
Roupas Ltda - ME - CNPJ: 00.219.460/0001-05, Jose Henrique Galvani - CPF: 234.846.406-34
e Heliane Leonel Raymundo Galvani - CPF: 813.460.347-53, porventura
existentes junto a instituições financeiras, incluindo cartões de crédito, agenciadores
de pagamento, administradores de consórcio."""

# 调整后的正则:先通过后视断言确认位置在executada(s):之后,再匹配CNPJ
pattern = r'(?<=executad\w(?:\(s\))?:.*?)CNPJ:? (?P<cnpj>\d+\.\d+\.\d+\/\d+-\d+)'

for item in regex.finditer(pattern, text, flags=regex.I|regex.S):
    print(item.groupdict())

运行结果

{'cnpj': '10.547.889/0001-85'}
{'cnpj': '00.219.460/0001-05'}

完全符合预期输出要求。

内容的提问来源于stack exchange,提问作者Daniel Bailo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 23:06:08