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

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

问题描述

类似于:

def match = "John 19" =~/(&name&)w+ (&age&d+)/定义名称 = match.namedef age = match.age

是否有一种非常棒的语法允许这样的事情(而不是我编造的虚构的 & 运算符?

解决方案

假设您使用的是 Java 7+,您可以:

def matcher = 'John 19' =~/(?w+) (?d+)/如果(匹配器.matches()){println "匹配"断言 matcher.group( 'name' ) == 'John'断言 matcher.group( 'age' ) == '19'}别的 {println "不匹配"}

如果您还没有使用 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天全站免登陆