How to convert String to GString and replace placeholder in Groovy?

I want to read String from a database and replace the placeholder by translating it to GString. Can I do this with Eval? Any other ideas?

String stringFromDatabase = 'Hello ${name}!' String name = 'world' assert 'Hello world!'== TODO 
+8
groovy
source share
2 answers

You can use the template framework in Groovy, so this solves your problem:

 String stringFromDatabase = 'Hello ${name}!' String name = 'world' def engine = new groovy.text.SimpleTemplateEngine() assert 'Hello world!'== engine.createTemplate(stringFromDatabase).make([name:name]).toString() 

You can find documents here: http://docs.groovy-lang.org/latest/html/documentation/template-engines.html#_introduction

The GString class is abstract, and the implementation of the abstract GStringImpl class works on arrays of strings that it receives from the analysis phase along with the values.

+9
source share

You must use a double-quoted string literal if you want to use placeholders.

The following should work:

 String name = 'world' String stringFromDatabase = "Hello ${name}!" //use double quotes assert 'Hello world!' == stringFromDatabase 

See the official Groovy String documentation for other ways you can do this.

0
source share

All Articles