I would like to substitute %s
with the value
<server>
<id>artifactory</id>
<username>%s</username>
<password>%s</password>
</server>
Is there any myString.format("name", "pass")
method in groovy?
Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes ('), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines.
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.
String interpolation. Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings.
Groovy has built-in support for string interpolation. All you need is to use a GString
:
def name = "name"
def pass = "pass"
String formatted = """
<server>
<id>artifactory</id>
<username>$name</username>
<password>$pass</password>
</server>
"""
If your values come as an array or collection, you can even use params[n]
instead of named variables ($name
), like this:
def params = ['name', 'pass']
String formatted = """
<server>
<id>artifactory</id>
<username>${params[0]}</username>
<password>${params[1]}</password>
</server>
"""
If your string needs to be externalized, you can use template engines
Beside this, you can use the normal Java String.format
:
def formatted = String.format(myString, "name", "pass")
groovy based on java and in java there is a format
method in String
class
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object...)
so this should work
def s='''<server>
<id>artifactory</id>
<username>%s</username>
<password>%s</password>
</server>'''
println String.format(s, "name", "pass")
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