【问题标题】:How to escape forward slash in the matches constraint如何在匹配约束中转义正斜杠
【发布时间】:2013-01-05 10:21:34
【问题描述】:

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

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

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

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

错误:unexpected char: '\'

【问题讨论】:

    标签: grails groovy grails-constraints


    【解决方案1】:

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

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

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

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

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

    要转义字符串中的字符,您必须使用\\(第一个\ 用于转义第二个\)。所以下面的表达式应该可以工作:

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

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

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

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

    【讨论】:

    • +1。 “斜线”语法确实有效,但您不需要前导 ~。在 groovy 中,/foo/ 只是字符串文字的另一种语法。 ~ 运算符可以放在任何字符串(单引号、双引号或斜线)前面作为Pattern.compile 的简写,将字符串转换为Pattern
    猜你喜欢
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2012-04-29
    相关资源
    最近更新 更多