展开文本中的环境变量 [英] Expand environment variables in text
问题描述
我正在尝试编写一个函数来执行Java中环境变量的替换.因此,如果我有一个看起来像这样的字符串:
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:
用户$ {USERNAME}的APPDATA路径为$ {APPDATA}.
User ${USERNAME}'s APPDATA path is ${APPDATA}.
我希望结果是:
用户msmith的APPDATA路径为C:\ Users \ msmith \ AppData \ Roaming.
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;
}
使用以上示例文本, matcher.matches()
返回false.但是,如果我的示例文本为 $ {APPDATA}
,则可以使用.
Using the above sample text, matcher.matches()
returns false. However if my sample text, is ${APPDATA}
it works.
任何人都可以帮忙吗?
推荐答案
You don't want to use matches()
. Matches will try to match the entire input string.
尝试根据图案匹配整个区域.
Attempts to match the entire region against the pattern.
您想要的是 while(matcher.find()){
.这将匹配您的模式的每个实例.请查看 的文档> find()
.
What you want is while(matcher.find()) {
. That will match each instance of your pattern. Check out the documentation for find()
.
在每次匹配中,第0组
将是整个匹配的字符串( $ {appdata}
),而第1组
将是 appdata
部分.
Within each match, group 0
will be the entire matched string (${appdata}
) and group 1
will be the appdata
part.
您的最终结果应类似于:
Your end result should look something like:
String pattern = "\\$\\{([A-Za-z0-9]+)\\}";
Pattern expr = Pattern.compile(pattern);
Matcher matcher = expr.matcher(text);
while (matcher.find()) {
String envValue = envMap.get(matcher.group(1).toUpperCase());
if (envValue == null) {
envValue = "";
} else {
envValue = envValue.replace("\\", "\\\\");
}
Pattern subexpr = Pattern.compile(Pattern.quote(matcher.group(0)));
text = subexpr.matcher(text).replaceAll(envValue);
}
这篇关于展开文本中的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!