Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: Variable Substitution in dynamic Strings

I'm currently facing a variable substitution related problem in groovy. While this is quite trivial:

Map map = [s1:"Hello", s2:"World"]
println "${map.s1} ${map.s2}!" // "Hello World!"

As this works, I'm pretty sure that something like this should work as well:

Map map = [s1:"Hello", s2:"World"]
def dynamic = loadStringFromFile();

println "${dynamic} ${dynamic.class}" // "${s1} ${s2}! (java.lang.String)"

// now the voodoo part
println applyVoodoo(dynamic, map) // "Hello World!"

Does anybody know how to get this working?

Cheers

like image 844
sfussenegger Avatar asked Sep 24 '09 15:09

sfussenegger


2 Answers

You would normally do this with Groovy Templates.

like image 124
John Wagenleitner Avatar answered Oct 19 '22 23:10

John Wagenleitner


dynamic.replaceAll(/\$\{(\w+)\}/) { m, k -> map[k] }
like image 20
sepp2k Avatar answered Oct 19 '22 23:10

sepp2k