Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing string in Groovy?

Tags:

parsing

groovy

I am new to Groovy and I am trying to parse header from my REST service response. The string is below:

[http://localhost:4545/third-party-web?code=IVJZw1]

I am trying to code IVJZw1.

It is easy and I hope I get help quick.

Azou

like image 317
Assane Diop Avatar asked Dec 13 '22 02:12

Assane Diop


2 Answers

If you want something quick and dirty, you can use a regex:

def str = '[http://localhost:4545/third-party-web?code=IVJZw1]'
def code = (str =~ /code=(\w*)/)[0][1]
assert code == 'IVJZw1'

There i assumed that the "code" parameter is composed of alphanumeric characters (\w).

However, if you find yourself extracting parameter values from URLs very often, this solution will get awfully dirty quite soon. Something like ataylor suggested will probably be more appropriate, specially if you can extract the logic of getting the URL parameters on a separate function. Maybe even a method on the URL class itself :D

import java.net.*

// Retrieves the query parameters of a URL a Map.
URL.metaClass.getQueryParams = { ->
    delegate.query.split('&').collectEntries { param -> 
        param.split('=').collect { URLDecoder.decode(it) }
    }.asImmutable()
}

// Then that method can be used directly on URLs :)
def str = '[http://localhost:4545/third-party-web?code=IVJZw1]'
def code = new URL(str[1..-2]).queryParams.code
assert code == 'IVJZw1'
like image 61
epidemian Avatar answered Feb 12 '23 18:02

epidemian


If the square brakets are stripped off, it's just an URL. You could try something like this:

import java.net.*
def str = '[http://localhost:4545/third-party-web?code=IVJZw1]'
def url = new URL(str.replaceFirst('^\\[', '').replaceFirst(']$', ''))
def paramMap = url.query.split('&').collectEntries { param -> 
    param.split('=').collect { URLDecoder.decode(it) }
}
assert paramMap['code'] == 'IVJZw1'
like image 42
ataylor Avatar answered Feb 12 '23 18:02

ataylor