Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string in groovy

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?

like image 806
Rudziankoŭ Avatar asked Oct 18 '18 08:10

Rudziankoŭ


People also ask

How do I write strings 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.

What is format method in string?

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.

What is string interpolation in Groovy?

String interpolation. Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings.


2 Answers

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")
like image 93
ernest_k Avatar answered Sep 20 '22 10:09

ernest_k


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")
like image 32
daggett Avatar answered Sep 18 '22 10:09

daggett