代码之家  ›  专栏  ›  技术社区  ›  Adam Smith

检查有多少正则表达式匹配组,然后使用它们

  •  0
  • Adam Smith  · 技术社区  · 7 年前

    我希望在Groovy中匹配正则表达式,检查返回了多少个组,然后使用其中一个组,但是得到:

    java.lang.IllegalStateException: No match found
    

    如果我打电话 match.groupCount() match.group(1)

    def match = "Some text" =~ /(text)/
    if (match.groupCount() >= 1) {
        print match.group()  // error
    }
    
    // or
    
    def match = "Some text" =~ /(text)/
    if (match) {
        print match.group()  // success
    }
    
    1 回复  |  直到 7 年前
        1
  •  -1
  •   daggett    7 年前

    你的第一个变体在调用前 groupCount() find() matches()

    def match = "Some text" =~ /(text)/
    if (match.find()) {
        println match.groupCount()
        print match.group()  // error
    }
    

    这个 if (match) {...} asBoolean() 那就是电话 查找() 在火柴上

    还有一些更简单的变体

    ("Some text 2 text" =~ /text/).each{
        println it
    }
    

    println (("Some text 2 text" =~ /text/).collect())