Are there named groups in Groovy regex pattern matches?

前端 未结 3 1694
小蘑菇
小蘑菇 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条回答
  • 2020-12-25 14:23

    This doesn't name the groups, but a closure does parameterise the match:

    ("John 19" =~ /(\w+) (\d+)/).each {match, name, age ->
      println match
      println name
      println age
    }
    

    which outputs:

    John 19
    John
    19
    

    This is a useful reference: http://naleid.com/blog/2008/05/19/dont-fear-the-regexp/

    0 讨论(0)
  • 2020-12-25 14:33

    Alternative:

    def foo = '''(id:(1 2 3)) OR (blubb)
    (id:(4 5 6)) OR (fasel)
    '''
    ​def matcher =  (foo =~ /\(id:\((.+)\)\) OR (.*)/)
    def (whole, bar, baz) = matcher[0]
    assert whole == '(id:(1 2 3)) OR (blubb)'
    assert bar == '1 2 3'
    assert baz == '(blubb)'
    
    (whole, bar, baz) = matcher[1]
    assert whole == '(id:(4 5 6)) OR (fasel)'
    assert bar == '4 5 6'
    assert baz == '(fasel)'
    
    0 讨论(0)
  • 2020-12-25 14:47

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

    def matcher = 'John 19' =~ /(?<name>\w+) (?<age>\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

    0 讨论(0)
提交回复
热议问题