regexgrailsgant

Regex to find pairs of strings


I have found this great gant script on http://blog.armbruster-it.de/2010/07/getting-a-list-of-all-i18n-properties-used-in-a-grails-application/ Thanks Stefan!

Description: create a list of all i18n properties used in groovy code and gsp templates

def properties = []

new File(".").eachFileRecurse {
    if (it.file) {
        switch (it) {
            case ~/.*\.groovy/:
                def matcher = it.text =~ /code:\s*["'](.*?)["']/
                matcher.each { properties << it[1] }
                break
            case ~/.*\.gsp/:
                def matcher = it.text =~ /code=["'](.*?)["']/
                matcher.each { properties << it[1] }
                break
        }
    }
}
println properties.sort().unique().join("\n")

I tried to extend it in the following way. Let's say we have soem message properties like:

message(code: 'product.label', default: 'Product')

What we want to have as output of the script something like:

product.label=Product

I tried to add some condition to the regex:

def matcher = it.text =~ /code=["'](.*?)["'] | default=\s*["'](.*?)["']/

and to fill it to properties. But as the regex does not find pairs of "code and default"-parts this is not going to work.

Any idea how to change the regex or the whole script to do this?


Solution

  • Your regular expression is incorrect. For the following message method call:

    message(code: 'product.label', default: 'Product')
    

    It should look like this:

    def properties = [:]
    def txt = "message(code: 'product.label', default: 'Product')"
    def matcher = txt =~ /code:\s*["'](.*?)["'].*default:\s*["'](.*?)["']/
    matcher.each{ properties[it[1]] = it[2] }
    assert properties == ['product.label':'Product']