Friday, May 19, 2017

Maven build, how to replace only a part of regexp match

The following configuration will be useful when you need to replace a subsection of a regular expression match in a file at maven build.

Usecase scenario:

Let's say you have a configuration file (conf.properties) with set of properties and you need to update the properties only related to ios.

Sample data:
carbon.device.mgt.input.adapter=false
carbon.device.mgt.ios.api=flase
carbon.device.mgt.ios.apns=false
carbon.device.mgt.ios.core=false
carbon.device.mgt.mobile.android=false
Expected outcome:
carbon.device.mgt.input.adapter=false
carbon.device.mgt.ios.api=true
carbon.device.mgt.ios.apns=true
carbon.device.mgt.ios.core=true
carbon.device.mgt.mobile.android=false
This is achievable by the maven-antrun-plugin.

Sample configuration:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.6</version>
    <executions>
        <execution>
            <id>default-feature-install</id>
            <phase>package</phase>
            <configuration>
                <target>
                    <replaceregexp file="conf.properties" match="(ios.*)false" replace="\1true" byline="true"/>
                </target>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
</plugin>
Regular expression justification:

  • match="(ios.*)false"
    • The following regular expression will select the string that contains "ios" and "false".
    • But we only need to replace the "false" value to "true" in the regular expression selection.
    • Therefore I have grouped the selection using brackets so that it can be referenced in the substitution expression.
  • replace="\1true"
    • In the following substituion string I have used the "\1" to define that I need to include the 1st group selection as part of the replacement string. 
    • The rest of the selection will get replaced by the new value.
Happy coding !!!


No comments:

Post a Comment