I'm trying to write a function to perform substitutions of environment variables in java. So if I had a string that looked like this:
User ${USERNAME}'s APPDATA path is ${APPDATA}.
I want the result to be:
User msmith's APPDATA path is C:\Users\msmith\AppData\Roaming.
So far my broken implementation looks like this:
public static String expandEnvVars(String text) {
Map<String, String> envMap = System.getenv();
String pattern = "\\$\\{([A-Za-z0-9]+)\\}";
Pattern expr = Pattern.compile(pattern);
Matcher matcher = expr.matcher(text);
if (matcher.matches()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
String envValue = envMap.get(matcher.group(i).toUpperCase());
if (envValue == null) {
envValue = "";
} else {
envValue = envValue.replace("\\", "\\\\");
}
Pattern subexpr = Pattern.compile("\\$\\{" + matcher.group(i) + "\\}");
text = subexpr.matcher(text).replaceAll(envValue);
}
}
return text;
}
Using the above sample text, matcher.matches()
returns false. However if my sample text, is ${APPDATA}
it works.
Can anyone help?