如何在匹配约束中转义正斜杠

zor*_*119 4 grails groovy grails-constraints

使用匹配约束时,如何在正则表达式中转义正斜杠?这是我试过的:

constraints {
    url (
        matches: "^http://www.google.com/$"
    )
}
Run Code Online (Sandbox Code Playgroud)

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

constraints {
    url (
        matches: "^http:\/\/www.google.com\/$"
    )
}
Run Code Online (Sandbox Code Playgroud)

错误: unexpected char: '\'

mic*_*cha 9

在用双引号("..")定义的字符串中,groovy用变量替换变量$.

def var = "world"
def str = "hello $var" // "hello world"
Run Code Online (Sandbox Code Playgroud)

在您的验证正则表达式中,这会导致错误.您希望使用$正则表达式而不是变量替换.为避免变量替换,您可以用单引号('..')定义字符串

def str = 'hello $var' // "hello $var"
Run Code Online (Sandbox Code Playgroud)

/在字符串中定义正则表达式时,您不需要转义,但是您应该转义..在正则表达式中.匹配任何字符.所以正则表达式^http://www.google.com/$匹配http://wwwAgoogleB.com/.

要转义必须使用的字符串内的字符\\(第一个\用于转义第二个字符串\).所以下面的表达式应该有效:

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

通常你也可以使用groovy正则表达式语法(/../).在这种情况下,正则表达式看起来像这样

~/^http:\/\/www\.google\.com\/$/
Run Code Online (Sandbox Code Playgroud)

你不需要双反斜杠来转义,但是你必须转义斜杠(因为它们用于终止正则表达式).但据我所知,这种语法不适用于grails的匹配约束.

  • +1."slashy-string"语法确实有效但你不需要领先的`~`.在groovy中,`/ foo /`只是字符串文字的另一种语法.`~`运算符可以在任何字符串前面(单引号,双引号或斜杠)作为`Pattern.compile`的简写,将字符串转换为`Pattern`. (3认同)