Home > Software design >  Replace paths using regex fails, what did I miss?
Replace paths using regex fails, what did I miss?

Time:10-30

I need to replace references to /devt/ with /Volumes/devt/ when tests are executed on a specific platform. So I tried: folder.replaceAll("(^|=)/devt/","\$1/Volumes/devt/") which seemed good, given that

  • the string could occur either at the start of the command or anywhere following a =
  • there is a chance that we could get /Volumes/devt/ as subject - in that case we don't want to do anything

This did not do anything. No error msg, but also no replacement. So I tried folder.replaceAll("^(?!/Volumes)/devt/","\$1/Volumes/devt/") but that failed with java.lang.IndexOutOfBoundsException: No group 1.

I tested those expression with a validator that did not complain. But I'm not sufficiently versed in the Jenkins/Groovy/Java-universe to know about special handling there...

CodePudding user response:

The ^(?!/Volumes)/devt/ regex is equal to ^/devt/ as /Volumes cannot be located at the same position with /devt/.

What you want to replace is /devt/ at the start of string or after a = sign, so all you need to use is

folder = folder.replaceAll("(?<![^=])/dev/", "/Volumes/devt/")

The (?<![^=])/dev/ regex matches /dev/ that is either at the start or is preceded with =. Therefore, no need to use a backreference in the replacement.

Do not forget that strings in Java are immutable, so you always need to assign the result to the variable to update its value.

CodePudding user response:

Thanks @Wiktor Stribiżew - the solution was actually even simpler:

where I wrote folder.replaceAll("(^|=)/devt/","\$1/Volumes/devt/") I should have assigned the result!

folder = folder.replaceAll("(^|=)/devt/","\$1/Volumes/devt/") fixed it. The regex itself was not the problem!

PS: that regex makes no sense!

Just a comment regarding Wiktor's comment: it makes sense. When looking at the folder structure from MacOS, the folder /devt/is addressed as /Volumes/devt/. So, when confronted with a call /devt/myscript val1=/devt/file1 val2=/Volumes/devt/file2", val2` does not need to be modified. My initial rx (as well as yours) takes care of that ;)

  • Related