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

使用re.compile匹配icode前缀时报_sre.SRE_Pattern不可迭代错误如何解决

问题原因
  • 你使用in关键字判断字符串是否符合正则规则是语法错误:in用于判断元素是否属于可迭代对象(列表、字符串、字典等),而re.compile()生成的是正则规则对象,不属于可迭代类型,因此触发_sre.SRE_Pattern is not iterable报错。
  • 你的需求是匹配icode的前缀,正好对应正则match()方法的特性:该方法默认从字符串开头匹配规则,不需要额外加^也能实现前缀匹配。
修复方案

两种写法按需选择即可:

写法1:最小改动(保留原有4个pattern定义)

仅修改匹配判断逻辑即可,额外加了str()转换避免icode为数字类型时的匹配报错:

def get_match_codes(icode):
    try:
       if pattern3.match(str(icode)) or pattern4.match(str(icode)):
          stype='straight'
       elif pattern2.match(str(icode)) or pattern1.match(str(icode)):
          stype='late'
       else:
          stype="none"
       return stype
    except Exception as e:
       return 'Error from get_match_codes' +str(e)

写法2:优化合并正则,代码更简洁

把同分类的前缀合并到同一个正则规则里,减少判断分支:

import numpy as np
import pandas as pd
import awswranger as wr
import re

# 同分类前缀用|分隔,合并为两个正则规则
straight_pattern = re.compile(r'^(3242444233|7634726472)')
late_pattern = re.compile(r'^(3233443446|3234444233)')

def get_match_codes(icode):
    try:
        icode_str = str(icode)
        if straight_pattern.match(icode_str):
            return 'straight'
        elif late_pattern.match(icode_str):
            return 'late'
        else:
            return 'none'
    except Exception as e:
       return f'Error from get_match_codes{str(e)}'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:45:10