Search code examples
regexgradlefiltercopy

Gradle copySpec: replaceToken for regex pattern


Gradle copySpec: how to replaceToken for regex pattern?

task myTask(type: Copy) {
   from ("/path/to") {
      include "*.txt"

      filter (ReplaceTokens, tokens : ["Hello(.+)World" : replacement]
   }

}

Regular expressions are not supported for the ReplaceToken.


Solution

  • The ReplaceTokens filter does not support regexes, just replacing fixed tokens with a prefix and a suffix.

    To use a regex, you can for example use filter { it.replaceAll(/Hello(.+)World/, replacement) }.

    Be aware that you should also set a filteringCharset, so that the files are handled with the correct encoding and not depending on the default charset of the JVM / OS you run the build on.