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
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With