Is there a way to declare the Groovy string format in a variable?
I currently have a fixed format for asset management code that uses the Groovy string format using a dollar sign:
def code = "ITN${departmentNumber}${randomString}"
A code will be generated that looks like this:
ITN120AHKXNMUHKL
However, I have a new requirement that the code format is customizable. I would like to demonstrate this functionality by allowing the user to set a custom format string like:
OCP $ {departmentNumber} XI $ {randomString}
PAN - $ {randomString}
The output will be:
OCP125XIBQHNKLAPICH
PAN-XJKLBPPJKLXHNJ
Which Groovy then interprets and replaces the corresponding variable value. Is this possible, or do I need to manually parse the placeholders and manually execute string.replace?
source to share
I believe that lazy evaluation of GString fits the bill :
deptNum = "C001"
randomStr = "wot"
def code = "ITN${deptNum}${->randomStr}"
assert code == "ITNC001wot"
randomStr = "qwop"
assert code == "ITNC001qwop"
source to share
I think the original poster wants to use a variable as a format string. The answer is that string interpolation only works if the format is a string literal. It seems like it should be downgraded at String.format
compile time. I ended up usingsprintf
baseUrl is a string containing http://example.com/foo/%s/%s
loaded from properties file
def operation = "tickle"
def target = "dog"
def url = sprintf(baseUrl, operation, target)
url
===> http://example.com/foo/tickle/dog
source to share
I suppose in this case you don't need to use lazy evaluation of GString, normal String.format()
from java will do it:
def format = 'ITN%sX%s'
def code = { def departmentNumber, def randomString -> String.format(format, departmentNumber, randomString) }
assert code('120AHK', 'NMUHKL') == 'ITN120AHKXNMUHKL'
format = 'OCP%sXI%s'
assert code('120AHK', 'NMUHKL') == 'OCP120AHKXINMUHKL'
Hope this helps.
source to share