jenkins - 在 Groovy 中使用分隔符拆分字符串并避免 IndexOutOfBoundsException

标签 jenkins groovy jenkins-pipeline jenkins-groovy groovy-console

我想将输入参数 inputDetails 拆分到单元级别。我正在使用 tokenize 来执行此操作。这是我的代码:

常规代码:

def inputDetails = "1234-a0-12;1111-b0-34";
def cDesc = inputDetails.tokenize(";");
for (int i=0; i<cDesc.size(); ++i)
{
    def cVer = cDesc.get(i);
    def cNum = cVer.tokenize("-");
    def a = cNum.get(0);
    def b = cNum.get(1);
    def c = cNum.get(2);

    println (" DEBUG : Input details are, ${a} : ${b} : ${c} \n");
}

输出:

 DEBUG : Input details are, 1234 : a0 : 12 

 DEBUG : Input details are, 1111 : b0 : 34

此输出是正确的且符合预期。但是,如果我将 Groovy 代码的第一行更改为以下内容:

def inputDetails = "1234-a0-12;1111-b0";

我收到以下错误消息:

 java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java_util_List$get$6.call(Unknown Source)
    at Script1.run(Script1.groovy:9)

如何修复它以防止出现 IndexOutOfBoundsException 同时支持 1234-a0-12;1111-b0-341234-a0-12 ;1111-b0 输入?

最佳答案

您可以使用 Groovy 的 multiple assignment从第二次标记化中安全地获取 3 个值的功能。考虑以下示例:

def inputDetails = "1234-a0-12;1111-b0-34"

def cDesc = inputDetails.tokenize(";")

cDesc.each { part ->
    def (p1, p2, p3) = part.tokenize('-')

    println "DEBUG: Input details are, ${p1} : ${p2} : ${p3}"
}

输出:

DEBUG: Input details are, 1234 : a0 : 12
DEBUG: Input details are, 1111 : b0 : 34

好处是这种方法可以防止 IndexOutOfBoundsExceptionNullPointerException。如果我们将第一行更改为

def inputDetails = "1234-a0-12;1111-b0"

结果是:

DEBUG: Input details are, 1234 : a0 : 12
DEBUG: Input details are, 1111 : b0 : null

关于jenkins - 在 Groovy 中使用分隔符拆分字符串并避免 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747128/

相关文章:

linux - redhat 中的 Perl 和 shell 脚本

groovy - 在 Groovy 中获取其名称的变量值

docker - 包含 Dockerfile、Jekinsfile、Kubernetes 部署 yaml、pip requirements.txt 和测试脚本的项目的目录结构?

jenkins - 如何在 jenkins 管道中连接两个 env 变量,中间有一个斜线?

java - 如何获取 Groovy 类的所有属性名称?

groovy - 在 Groovy 和 Jenkins Pipeline 中组合多个 collectEntries

通过 Jenkins(使用 Maven)在 Tomcat7 上部署 war 时,java.net.socketexception 连接由对等套接字写入错误重置

Jenkins:Github webhook 不会触发任何工作

tomcat - 从 ant 脚本启动 tomcat

java - 从 Java/Groovy 运行复合 shell 命令