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

Groovy列表元素索引获取异常:curMonth匹配失败如何修复?

问题描述

通过以下代码获取curMonth变量:

def String curMonth = cube.getSubstitutionVariableValue('StartMth').toString()

该变量输出结果显示为'P09',但后续执行这段代码时:

List<String> moDictionary = ['P01','P02','P03','P04','P05','P06','P07','P08','P09','P10','P11','P12','P13']

int idxStartMonth = moDictionary.indexOf(curMonth)

List openMonths = moDictionary[idxStartMonth..12]

打印idxStartMonth得到的结果是-1,而非预期的8;但把curMonth替换为硬编码的'P09'时,能得到正确结果。需要修复代码让curMonth能被正确匹配。

修复方案

问题核心是curMonth的实际值和硬编码的'P09'并非完全相等,大概率是包含了不可见字符(比如首尾空格、换行符、制表符),或者存在编码/类型差异。可以用以下方法解决:

  • 清理首尾空白字符
    在获取变量后直接调用trim()方法,去除首尾的空白类不可见字符:

    def String curMonth = cube.getSubstitutionVariableValue('StartMth').toString().trim()
    
  • 提取标准格式字符串
    如果变量值可能夹杂其他无关内容,用正则提取符合PXX格式的部分:

    def rawValue = cube.getSubstitutionVariableValue('StartMth').toString()
    def matcher = (rawValue =~ /P\d{2}/)
    def curMonth = matcher.find() ? matcher.group() : ''
    
  • 排查变量实际内容
    若不确定问题根源,可打印变量的长度和每个字符的ASCII码,对比硬编码值的输出找差异:

    def curMonth = cube.getSubstitutionVariableValue('StartMth').toString()
    println "curMonth长度:${curMonth.length()}"
    curMonth.each { char c -> println "字符:$c,ASCII码:${(int)c}" }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:15:22