【问题标题】:What's wrong with my Groovy regex?我的 Groovy 正则表达式有什么问题?
【发布时间】:2014-05-07 17:59:58
【问题描述】:

这是我的代码:

String myRegex = "*cow"
String name = "SHIRACOWPEPPER"
name = name.toLowerCase()

if(!name || name.matches(myRegex)) {
    return true
}

当我运行它时,我得到一个PatternSyntaxException: Dangling meta character '*' near index 0 *cow ^ 错误。想法?

【问题讨论】:

    标签: regex string groovy patternsyntaxexception


    【解决方案1】:

    * 是一个元字符,表示您之前匹配的内容“零次或多次”,但在这种情况下,没有可匹配的内容。这应该可行:

    String myRegex = ".*cow"
    String name = "SHIRACOWPEPPER"
    name = name.toLowerCase()
    
    if(!name || name.matches(myRegex)) {
        return true
    }
    

    欲了解更多信息,请参阅documentation

    【讨论】:

    • 你也可以!name || name ==~ myRegex
    【解决方案2】:

    您可能想说String myRegex = ".*cow",这意味着cow 之前的任何数字字符是后缀

    【讨论】:

      猜你喜欢
      • 2013-09-13
      • 2012-02-24
      • 2013-04-11
      • 2014-08-26
      • 2020-08-07
      相关资源
      最近更新 更多