如何将$ {Month}替换为字符串?

Rad*_*dek 0 groovy placeholder str-replace

我想在配置文件中为某些变量创建"自定义"占位符.我以为我会使用这种语法${Variable_name}.但是当我想用值替换占位符时,我无法使其工作.我不需要打印最终值,但将其传递给另一个变量.我只使用println进行调试.字符串变量tmp包含从xml配置文件中读取的字符串.所以我需要tmp2来替换占位符的正确字符串.

String Month = "October"
String tmp = 'This is ${Month} - a month of Love'
String tmp2 = tmp

println tmp2

//println tmp.replaceAll(~/${Month}/,Month)
println tmp.replaceAll("${Month}",Month)   //prints This is ${Month} of Love
println tmp.replaceAll('${Month}',Month)   // throws an error "WARNING: Sanitizing stacktrace:java.util.regex.PatternSyntaxException: Illegal repetition near index 0" 
// desired result to be printed is "This is October
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我使其工作或理解吗?我想我可以用其他一些字符来标记变量.配置文件保存为XML.

UPDATE

我希望这段代码能更好地解释我想要实现的目标

String Month = "October"


// content of the file (c:/tmp/conf.txt) is --> This is ${Month} - a month of Love
// I want f2 to contain "This is October - a month of Love"
// println is not a choice as I don't use println in my code
// I need a variable to contain the final string

def f2 = new File('c:/tmp/conf.txt') //use same path
println f2.text
Run Code Online (Sandbox Code Playgroud)

Dyl*_*gte 8

您可以使用Java String格式方法:

String month = 'October'
String tmp = 'This is %s - a month of Love'
String tmp2 = String.format(tmp, month)
Run Code Online (Sandbox Code Playgroud)

或者保留使用${Month}你可以使用:

import groovy.text.SimpleTemplateEngine
String month = 'October'
String tmp = 'This is ${Month} - a month of Love'
String tmp2 = new SimpleTemplateEngine().createTemplate(tmp).make(Month:month)
Run Code Online (Sandbox Code Playgroud)


Bal*_*Rog 5

如果你真的想要对文件的内容使用Groovy的GString语法(类似shell的"${var}"变量替换),你想要的是GStringTemplateEngine.话虽如此,与常规编译时GString工具不同,引擎本身对您的本地变量环境一无所知,因此在执行引擎(make()方法)时必须传入替换值的映射.这是它的样子:

import groovy.text.GStringTemplateEngine

def replacements = [Month:'October']
def file = new File('template.txt')
def engine = new GStringTemplateEngine()
def template = engine.createTemplate(file).make(replacements)
println template
Run Code Online (Sandbox Code Playgroud)

鉴于文件内容:

This is ${Month} - a month of Love
Run Code Online (Sandbox Code Playgroud)

打印出以下结果:

This is October - a month of Love
Run Code Online (Sandbox Code Playgroud)