Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

java - Expand environment variables in text

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:UsersmsmithAppDataRoaming.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

What you want is while(matcher.find()) {. That will match each instance of your pattern. Check out the documentation for find().

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...