您不想使用
matches()。匹配项将尝试匹配整个输入字符串。
尝试根据图案匹配整个区域。
你想要的是
while(matcher.find()){。这将匹配您的模式的每个实例。请查看的文档find()。
在每个匹配项中,
group 0将是整个匹配的字符串(
${appdata}),group 1并将是
appdata一部分。
您的最终结果应类似于:
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);}


