0lukasz0
0lukasz0

Reputation: 3267

Ant building script using groovy and regular expressions, how to build pattern using string value?

How to use string value as a part of regular expression in groovy? I'am writing ant build script using groovy, here is some snapshot:

<target name="groovy.showProperties">
    <groovy>
        class ShowProperties extends org.apache.tools.ant.Task {
            String nameMatch;   

            public void execute() {
                    project.properties.each
                        {prop ->
                           //I don't know how to obtain nameMatch value
                            if(prop.key ==~ /.*nameMatch.*/) 
                            {
                                println prop;
                            }
                        };

            }
        }
        project.addTaskDefinition('dump', ShowProperties)
    </groovy>

    <echo>example:</echo>
    <dump nameMatch="lang"/>
</target>

Upvotes: 0

Views: 557

Answers (2)

tim_yates
tim_yates

Reputation: 171084

It should be:

/.*${nameMatch}.*/

Does that not work?

Edit:

Taking your example task, and wrapping it in a valid build.xml like so:

<?xml version="1.0" encoding="UTF-8"?>
<project name="ItWorks" basedir=".">
    <property environment="env"/>

    <path id="lib.path">
        <fileset dir="${env.GROOVY_HOME}">
            <include name="lib/*.jar"/>
        </fileset>
    </path>

    <taskdef name="groovy"
             classname="org.codehaus.groovy.ant.Groovy"
             classpathref="lib.path"/>

    <target name="groovy.showProperties">
        <groovy>
            class ShowProperties extends org.apache.tools.ant.Task {
                String nameMatch;   

                public void execute() {
                    project.properties.each { prop ->
                        if( prop.key ==~ /.*${nameMatch}.*/ ) {
                            println prop
                        }
                    }
                }
            }
            project.addTaskDefinition('dump', ShowProperties)
        </groovy>

        <echo>example:</echo>
        <dump nameMatch="lang"/>
    </target>
</project>

I can then do:

ant groovy.showProperties

And I get the output:

Buildfile: /Users/tim/Code/test/build.xml

groovy.showProperties:
     [echo] example:
     [dump] user.language=en

BUILD SUCCESSFUL
Total time: 1 second

No parse errors or anything... What version of Groovy are you using?

Upvotes: 1

0lukasz0
0lukasz0

Reputation: 3267

I eventually found the solution:

in this simple example sufficient is:

prop.key =~ nameMatch

however, more generic approach would be:

prop.key ==~ ".*"+nameMatch+".*"

second example is more flexible as you can add other regex expressions by simply building a string.

Upvotes: 0

Related Questions