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.
~
. 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 forPattern.compile
to turn the string into aPattern
. – Mosora