Filtering files using regular expressions


(Brandon Murray) #1

Hello,

I’m converting the following ant code to gradle and I’m unable to figure out how to do the regex portion in gradle:

<copy...>
                    <filterchain>
                        <striplinecomments>
                            <comment value="#"/>
                        </striplinecomments>
                        <tokenfilter>
                            <ignoreBlank/>
                        </tokenfilter>
                        <replaceregex pattern="\s*(\S+)\s*="
                            replace="@@KEY.\1@@="/>
                    </filterchain>
                </copy>

gradle code: …

def regexp = new org.apache.tools.ant.types.RegularExpression()
    regexp.pattern = '[^ \n\t\r]+'
    filter(org.apache.tools.ant.filters.StripLineComments, comments: ["#"])
    filter(org.apache.tools.ant.filters.LineContainsRegExp, regexps:[regexp])
    // how to do regex replacement filter?

Thank you in advance!


(Gary Hale) #2

I find the filter closure form the easiest to use for this sort of thing. You should be able to do something like this:

project.task('myCopy', type: Copy) {
    from someDir
    into someOtherDir
    filter { line ->
      line.replaceAll("#.*","")
    }
  }

Point is, the filter closure gives you each line as as string where you can then manipulate it any way you want to and return the modified result.


(Brandon Murray) #3

Thanks Gary. The filter closure did the trick:

filter { String line ->
        line.replaceAll("\s*(\S+)\s*=", "@@KEY.\$1@@=")
    }

(naama.zuessman) #4

Hi,

After playing around with it, this is what worked for me:

def param = new org.apache.tools.ant.types.Parameter()

param.type = ‘comment’

param.value = ‘*’

filter(StripLineComments, parameters:[param])