Ant Regex Replacement Issue

Hi i want to replace/add (-SNAPSHOT) to a version from pom.xml. If the version is 1.1.1 i want 1.1.1-SNAPSHOT and when it is already SNAPSHOT to remain the same.

Currently i have this

<propertyregex property="snapshotVersionRepl"
                              input="${pom.project.version}"
                              regexp="(.*)(-SNAPSHOT)?"
                              replace="\1-SNAPSHOT"
                              casesensitive="false" />

But with input 1.0.0 i get 1.0.0-SNAPSHOT-SNAPSHOT , and with 1.0.0-SNAPSHOT i get 1.0.0-SNAPSHOT-SNAPSHOT-SNAPSHOT.

Upvotes: 0

Views: 169

Answers (2)

CAustin
CAustin

Reputation: 4614

First, I would recommend avoiding ant-contrib, as it tends to promote bad practices in Ant scripts. Any sort of string manipulation can be accomplished through native Ant's filterchain types.

Regarding your regex, Wiktor's pattern works, but in this case I would prefer to use negative lookbehind.

Test Target:

<target name="replace-version">
    <property name="pom.project.version1" value="1.1.1" />

    <loadresource property="snapshotVersionRepl1">
        <propertyresource name="pom.project.version1" />
        <filterchain>
            <tokenfilter>
                <replaceregex pattern="(.*)(?&lt;!-SNAPSHOT)$" replace="\1-SNAPSHOT" />
            </tokenfilter>
        </filterchain>
    </loadresource>

    <echo>${snapshotVersionRepl1}</echo>

    <property name="pom.project.version2" value="1.1.1-SNAPSHOT" />

    <loadresource property="snapshotVersionRepl2">
        <propertyresource name="pom.project.version2" />
        <filterchain>
            <tokenfilter>
                <replaceregex pattern="(.*)(?&lt;!-SNAPSHOT)$" replace="\1-SNAPSHOT" />
            </tokenfilter>
        </filterchain>
    </loadresource>

    <echo>${snapshotVersionRepl2}</echo>
</target>

Output:

 [echo] 1.1.1-SNAPSHOT
 [echo] 1.1.1-SNAPSHOT

Note that &lt; is used in place of < to avoid breaking the XML syntax.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You may fix the pattern by adding anchors and making the first .* lazy:

regexp="^(.*?)(-SNAPSHOT)?$"

See the regex demo

Details

  • ^ - start of string
  • (.*?) - Group 1: any 0+ chars other than line break chars, as few as possible
  • (-SNAPSHOT)? - an optional -SNAPSHOT sequence
  • $ - end of string.

Upvotes: 1

Related Questions