CodeMed
CodeMed

Reputation: 9205

Attempt to split string on '//' in Jenkinsfile splits on '/' instead

What is the correct way to tokenize a string on double-forward-slash // in a Jenkinsfile?

The example below results in the string being tokenized on single-forward-slash / instead, which is not the desired behavior.


Jenkinsfile

An abbreviated, over-simplified example of the Jenkinsfile containing the relevant part is:

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
    }
}


The Logs:

The log output from the preceding is:

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]

Note that the logs show that the string is being tokeni on / instead of on //.

Upvotes: 1

Views: 9453

Answers (1)

anubhava
anubhava

Reputation: 786101

tokenize takes string as optional argument that may contain 1 or more characters as delimiters. It treats each character in string argument as separate delimiter so // is effectively same as /

To split on //, you may use split that supports regex:

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

Code Demo

Upvotes: 3

Related Questions