Search code examples
groovygroovy-console

Groovy regex parse value


I am trying to parse the below item using regex

Input field is

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

Output needed is

  • Location = Chesthunt
  • state = Herts
  • Country = GB

Code which i tried to retreive the state is

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

I am getting this as output when i print the location value

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

I tried using the parse method

if (location) {

   location = location[0][0]

}

I am getting the output as l=chesthunt where i need to get only the chesthunt. Could you please assist as i am new to groovy/regex


Solution

  • Given:

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

    You can do:

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

    this ~/l=([^\s,]+)/ looks for something starting with l=, and then captures up until whitespace or a comma