Search code examples
javamavenescapingbackslashmaven-resources-plugin

How to escape backslashes in a filtered properties files with Maven?


My pom.xml file looks like this:

<testResource>
    <directory>src/test/resources</directory>
    <filtering>true</filtering>
    <includes>
        <include>env.properties</include>
    </includes>
</testResource>

My env.properties looks like this:

my.path=${project.build.directory}

When I build the project, the env.properties is generated like below:

my.path=C:\\path\\to\\directory

How can I get the result below instead?

my.path=C:\\\\path\\\\to\\\\directory

Solution

  • This is a weird thing to want to do, but you could use the build-helper-maven-plugin:regex-property goal. This goal enables the creation of a Maven property which is the result of applying a regular expression to some value, possibly with a replacement.

    In this case, the regular expression would replace all blackslashes, i.e. \\ since they need to be escaped inside the regular expression, and the replacement would be the 4 backslashes. Note that the plugin automatically escapes the regular expression for Java, so you don't need to also Java-escape it.

    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>build-helper-maven-plugin</artifactId>
      <version>1.12</version>
      <executions>
        <execution>
          <id>escape-baskslashes</id>
          <phase>validate</phase>
          <goals>
            <goal>regex-property</goal>
          </goals>
          <configuration>
            <value>${project.build.directory}</value>
            <regex>\\</regex>
            <replacement>\\\\\\\\</replacement>
            <name>escapedBuildDirectory</name>
            <failIfNoMatch>false</failIfNoMatch>
          </configuration>
        </execution>
      </executions>
    </plugin>
    

    This will store the wanted path inside the escapedBuildDirectory property, that you can later use as a standard Maven property like ${escapedBuildDirectory}, inside your resource file. The property is created in the validate phase, which is the first phase invoked by Maven during the build, so that it could also be used anywhere else, as a plugin parameter.