Python正则匹配问题:如何精准提取functest与指定数字间内容?
解决Python正则提取functest与指定数字间内容的问题
问题分析
你当前的正则r'functest(.*?)1'用了惰性匹配.*?,但它不会排除中间出现的functest,导致匹配范围跨过多个functest条目,最终捕获了多余内容。
解决方案
修改正则表达式,确保捕获内容时不会跨过新的functest,同时跳过functest后的空格,精准提取目标内容:
import re test_str = 'functest exampleOne [2] functest exampleTwo [1] functest exampleOne throw [2] functest exampleThree [1]' # 提取functest与1之间的内容,且中间不包含functest testVariable = re.findall(r'functest\s*((?:(?!functest).)*?)1', test_str) print(testVariable)
输出结果:
['exampleTwo [', 'exampleThree [']
正则说明
functest:匹配固定前缀\s*:跳过functest与目标内容之间的任意空格(避免捕获结果带前导空格)(?:(?!functest).)*?:核心匹配逻辑,(?!functest)是负向预查,确保当前位置后不会出现functest,.*?保持惰性匹配,只匹配到最近的1为止1:指定要匹配的结束数字(按需替换为2、3即可提取对应内容)
按需切换目标数字
如果需要提取与2之间的内容,只需把正则中的1替换为2:
testVariable = re.findall(r'functest\s*((?:(?!functest).)*?)2', test_str) # 输出:['exampleOne [', 'exampleOne throw [']
内容的提问来源于stack exchange,提问作者Marcel Olaru
相关产品推荐
相关产品推荐

