首页 > 解决方案 > 尝试在 Jenkinsfile 中的 '//' 上拆分字符串,而不是在 '/' 上拆分

问题描述

//在 a中的双正斜杠上标记字符串的正确方法是Jenkinsfile什么?

下面的示例导致字符串在单正斜杠上被标记/,这不是所需的行为。


詹金斯文件

Jenkinsfile包含相关部分的 一个简短的、过度简化的示例是:

node {
    // Clean workspace before doing anything
    deleteDir()

    try {
        stage ('Clone') {
            def theURL = "http://<ip-on-lan>:<port-num>/path/to/some.asset"
            sh "echo 'theURL is: ${theURL}'"
            def tokenizedURL = theURL.tokenize('//')
            sh "echo 'tokenizedURL is: ${tokenizedURL}'"
        }
    } catch (err) {
        currentBuild.result = 'FAILED'
        throw err
    }
}


日志:

前面的日志输出是:

echo 'theURL is: http://<ip-on-lan>:<port-num>/path/to/some.asset'— Shell Script<1s
    [ne_Branch-Name-M2X23QGNMETLDZWFK7IXVZQRCNSWYNTDFJZU54VP7DMIOD6Z4DGA] Running shell script
    + echo theURL is: http://<ip-on-lan>:<port-num>/path/to/some.asset
    theURL is: http://<ip-on-lan>:<port-num>/path/to/some.asset

echo 'tokenizedURL is: [http:, <ip-on-lan>:<port-num>, path, to, some.asset]'— Shell Script<1s  
    [ne_Branch-Name-M2X23QGNMETLDZWFK7IXVZQRCNSWYNTDFJZU54VP7DMIOD6Z4DGA] Running shell script
    + echo tokenizedURL is: [http:, <ip-on-lan>:<port-num>, path, to, some.asset]
    tokenizedURL is: [http:, <ip-on-lan>:<port-num>, path, to, some.asset]

请注意,日志显示字符串正在 tokeni on/而不是 on //

标签: regexjenkinsgroovyjenkins-pipeline

解决方案


tokenize将字符串作为可选参数,可以包含 1 个或多个字符作为分隔符。它将字符串参数中的每个字符视为单独的分隔符,因此// 实际上/

要拆分//,您可以使用split支持正则表达式的:

theURL.split(/\/{2}/)  

代码演示


推荐阅读