首页 > 解决方案 > Groovy 正则表达式解析值

问题描述

我正在尝试使用正则表达式解析以下项目

输入字段是

def details = "jurisdictionOfIncorporationCountryName=GB, l=Cheshunt, st=Herts, c=GB"

需要的输出是

我试图检索状态的代码是

def location= subject =~/([l][=])\w+/

当我打印位置值时,我将其作为输出

r[pattern=([l][=])\w+ region=0,192 lastmatch=l=Cheshunt]

我尝试使用解析方法

if (location) {

   location = location[0][0]

}

我得到的输出为 l=chesthunt,我只需要得到 Chesthunt。你能帮忙吗,因为我是 groovy/regex 的新手

标签: groovygroovy-console

解决方案


鉴于:

def details = "jurisdictionOfIncorporationCountryName=GB, l=Cheshunt, st=Herts, c=GB"

你可以做:

def location = details.find(~/l=([^\s,]+)/) { it[1] }

~/l=([^\s,]+)/会查找以 开头的l=内容,然后一直捕获到空格或逗号


推荐阅读