Chel MS
Chel MS

Reputation: 466

Groovy - Split a string at last occurrence of colon

I'm trying to get the image and tag name from the registry URL in my groovy script but would like to do it in a single command, is it possible ?

Something like this

def registry_url = 'klp.lab.eu.org:1234/repo_list/EU/node:1.1-alpine'

def (image, tag) = registry_url.split( ':' )

Should give me klp.lab.eu.org:1234/repo_list/EU/node and 1.1-alpine

I'm aware of tokenize and can retrieve the tag value using registry_url.tokenize( ':' )[-1] but I'm not sure how to extract the image name.

Upvotes: 0

Views: 376

Answers (1)

Paul King
Paul King

Reputation: 1026

The find operator is easier to use than split for this case ('.' is greedy so you get the last colon):

def registry_url = 'klp.lab.eu.org:1234/repo_list/EU/node:1.1-alpine'
def (_, image, tag) = (registry_url =~ '(.*):(.*)')[0]
assert image == 'klp.lab.eu.org:1234/repo_list/EU/node'
assert tag == '1.1-alpine'

An alternative would be to use lastIndexOf (using Groovy 4 range syntax):

def registry_url = 'klp.lab.eu.org:1234/repo_list/EU/node:1.1-alpine'
def lastColon = registry_url.lastIndexOf(':')
def (image, tag) = registry_url.with{ [it[0..<lastColon], it[lastColon<..-1]] }

You can persevere with split if you wish:

def registry_url = 'klp.lab.eu.org:1234/repo_list/EU/node:1.1-alpine'
def parts = registry_url.split(':')
def (image, tag) = parts.with{ [it[0..-2].join(':'), it[-1]] }

Upvotes: 2

Related Questions