grailsgroovygrails-constraints

How to escape forward slash in the matches constraint


How can I escape the forward slashes in the regex when using the matches constraint? This is what I tried:

constraints {
    url (
        matches: "^http://www.google.com/$"
    )
}

Error: solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}"

constraints {
    url (
        matches: "^http:\/\/www.google.com\/$"
    )
}

Error: unexpected char: '\'


Solution

  • In strings defined with double quotes ("..") groovy replaces variables with $.

    def var = "world"
    def str = "hello $var" // "hello world"
    

    In your validation regex this is causing an error. You want to use the $ for a regular expression and not for variable replacement. To avoid variable replacement you can define strings in single quotes ('..')

    def str = 'hello $var' // "hello $var"
    

    You don't need to escape / when defining the regular expression inside a string but you you should escape .. In a regular expression . matches any character. So the regular expression ^http://www.google.com/$ matches http://wwwAgoogleB.com/.

    To escape a character inside a string you have to use \\ (the first \ is for escaping the second \). So the following expression should work:

    static constraints = {
        name (
            matches: '^http://www\\.google\\.com/$'
        )
    }
    

    Normally you could also use the groovy regular expression syntax (/../). It this case the regular expression would look like this

    ~/^http:\/\/www\.google\.com\/$/
    

    You don't need double backslashes for escaping but therefore you have to escape slashes (because they are used for terminating the regular expression). But as far as I know this syntax does not work with the matches constraint from grails.