How to escape forward slash in the matches constraint
Asked Answered
D

1

5

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: '\'

Detestation answered 5/1, 2013 at 10:21 Comment(0)
E
10

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.

Elude answered 5/1, 2013 at 10:50 Comment(1)
+1. "slashy-string" syntax does work but you don't need the leading ~. In groovy /foo/ is just an alternative syntax for string literals. The ~ operator can go in front of any string (single quoted, double quoted or slashy) as a shorthand for Pattern.compile to turn the string into a Pattern.Mosora

© 2022 - 2024 — McMap. All rights reserved.