Home > database >  Using replaceAll with a closure in Groovy
Using replaceAll with a closure in Groovy

Time:09-27

I have some Groovy code (actually from a Jenkinsfile):

           fileNew = fileOld.replaceAll("((D:)((.*)\\\\(.*))*)") {
                    it[0].replaceAll("D:", "/xxx/yyyy")
                    it[0].replaceAll("\\\\", "/")
            }
            writeFile file: 'my-output-file', text: fileNew

The code correctly matches the lines marked by the pattern in fileOld.replaceAll (as shown if I println it[0]) but there is no replacement in the written file. How can I get that to work?

CodePudding user response:

From what I'm seeing in the docs here it wouldn't work to call replaceAll inside of the replaceAll closure. I think maybe you just need to do two separate replaceAll calls, searching for the "D:" and "\\\\" separately.

CodePudding user response:

I was messing around with some different things and maybe using the original replaceAll would work.

fileNew = fileOld.replaceAll("((D:)((.*)\\\\(.*))*)") {
     it[0] = it[0].replace("D:", "/xxx/yyyy")
     it[0].replace("\\\\", "/")
}

That worked for me but I wasn't positive what fileOld would look like so I had to guess a little there.

  • Related