【问题标题】:Replace environment variable place-holders with their actual value?用它们的实际值替换环境变量占位符?
【发布时间】:2014-12-09 03:33:32
【问题描述】:

在我的 Application.properties 文件中,我正在使用类似的键和值

report.custom.templates.path=${CATALINA_HOME}\\\\Medic\\\\src\\\\main\\\\reports\\\\AllReports\\\\

我需要将${CATALINA_HOME} 替换为其实际路径:

{CATALINA_HOME} = C:\Users\s57893\softwares\apache-tomcat-7.0.27

这是我的代码:

public class ReadEnvironmentVar {  

 public static void main(String args[]) {

    String path = getConfigBundle().getString("report.custom.templates.path");
    System.out.println("Application Resources : " + path);
    String actualPath = resolveEnvVars(path);
    System.out.println("Actual Path : " + actualPath);

   }

private static ResourceBundle getConfigBundle() {
    return ResourceBundle.getBundle("medicweb");
 }

private static String resolveEnvVars(String input) {
    if (null == input) {
        return null;
     }

    Pattern p = Pattern.compile("\\$\\{(\\w+)\\}|\\$(\\w+)");
    Matcher m = p.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String envVarName = null == m.group(1) ? m.group(2) : m.group(1);
        String envVarValue = System.getenv(envVarName);
        m.appendReplacement(sb, null == envVarValue ? "" : envVarValue);
     }
    m.appendTail(sb);
    return sb.toString();
  }
}

从我的代码中,我得到的结果是 -

实际路径:

 C:Userss57893softwaresapache-tomcat-7.0.27\Medic\src\main\reports\AllReports\

但我需要结果为 -

实际路径:

C:\Users\s57893\softwares\apache-tomcat-7.0.27\Medic\src\main\reports\AllReports\

请给我一个例子?

【问题讨论】:

    标签: java regex string pattern-matching environment-variables


    【解决方案1】:

    由于appendReplacement() 的工作方式,您需要转义在环境变量中找到的反斜杠。来自the Javadocs

    请注意,替换字符串中的反斜杠 (\) 和美元符号 ($) 可能会导致结果与将其视为文字替换字符串时的结果不同。如上所述,美元符号可以被视为对捕获的子序列的引用,和反斜杠用于转义替换字符串中的文字字符。

    我会使用:

    m.appendReplacement(sb, 
        null == envVarValue ? "" : Matcher.quoteReplacement(envVarValue));
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 2017-11-30
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多