java - 用实际值替换环境变量占位符?

标签 java regex string pattern-matching environment-variables

在我的 Application.properties 文件中,我使用了这样的键和值

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

I need to replace the ${CATALINA_HOME} with its actual path:

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

Here is my code:

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\

请给我一个例子?

最佳答案

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

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

我会使用:

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

关于java - 用实际值替换环境变量占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359138/

相关文章:

java - 试图让字符串进入 Intent

java - 在非组件对象上使用 Spring @Value

regex - 来自标准输出的ansible解析文本字符串

c# - 用于验证具有一个空格和一个可选特殊字符的数字的正则表达式

c - 如何从命令行参数读取字符后的字符?

java - Java中自动加载特定父类(super class)的子类的工厂类?

java - 关于jredis性能的问题

javascript - 使用正则表达式从字符串中提取图像 url

c++ - 使用初始值设定项列表从多个字符数组构造 std::string

javascript - 使用 jquery 或 javascript 将逗号分隔的键和值字符串转换为对象