Groovy正则表达式模式匹配中是否有命名组? [英] Are there named groups in Groovy regex pattern matches?

查看:93
本文介绍了Groovy正则表达式模式匹配中是否有命名组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似的东西:

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

是否有一种通用的语法允许这样的事情(而不是我组成的虚构的&运算符?

解决方案

假设您使用的是Java 7+,则可以执行以下操作:

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"
}

如果您还没有使用Java 7,则需要第三方正则表达式库

Something like:

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

Is there a groovy syntax that allows for something like this (instead of of the fictional & operator I made up?

解决方案

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

这篇关于Groovy正则表达式模式匹配中是否有命名组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆