Are there named groups in Groovy regex pattern matches?

前端 未结 3 1716
小蘑菇
小蘑菇 2020-12-25 14:11

Something like:

def match = \"John 19\" =~ /(&name&)\\w+ (&age&\\d+)/
def name = match.name
def age = match.age

Is there a

3条回答
  •  猫巷女王i
    2020-12-25 14:47

    Assuming you are using on Java 7+, you can do:

    def matcher = 'John 19' =~ /(?\w+) (?\d+)/
    if( matcher.matches() ) {
      println "Matches"
      assert matcher.group( 'name' ) == 'John'
      assert matcher.group( 'age' ) == '19'
    }
    else {
      println "No Match"
    }
    

    If you are not on java 7 yet, you'd need a third party regex library

提交回复
热议问题