16

I am trying to find environment variables in input and replace them with values.

The pattern of env variable is ${\\.}

Pattern myPattern = Pattern.compile( "(${\\.})" );
String line ="${env1}sojods${env2}${env3}";

How can I replace env1 with 1 and env2 with 2 and env3 with 3, so that after this I will have a new string 1sojods23?

2
  • Your example suggests the pattern should be ${[^}]+} or similar rather than ${\\.}. Mar 7, 2012 at 17:00
  • Is the goal to collapse 'envN' down to 'N', or to replace 'envN' with the value assigned to envN in the environment/system properties? Mar 7, 2012 at 17:13

7 Answers 7

63

Strings in Java are immutable, which makes this somewhat tricky if you are talking about an arbitrary number of things you need to find and replace.

Specifically you need to define your replacements in a Map, use a StringBuilder (before Java 9, less performant StringBuffer should have been used) and the appendReplacements() and appendTail() methods from Matcher. The final result will be stored in your StringBuilder (or StringBuffer).

Map<String, String> replacements = new HashMap<String, String>() {{
    put("${env1}", "1");
    put("${env2}", "2");
    put("${env3}", "3");
}};

String line ="${env1}sojods${env2}${env3}";
String rx = "(\\$\\{[^}]+\\})";

StringBuilder sb = new StringBuilder(); //use StringBuffer before Java 9
Pattern p = Pattern.compile(rx);
Matcher m = p.matcher(line);

while (m.find())
{
    // Avoids throwing a NullPointerException in the case that you
    // Don't have a replacement defined in the map for the match
    String repString = replacements.get(m.group(1));
    if (repString != null)    
        m.appendReplacement(sb, repString);
}
m.appendTail(sb);

System.out.println(sb.toString());

Output:

1sojods23
2
  • 1
    Beautiful and elegant ... and thinking I had so much ugly code out there trying to do the same using basic string operations ... Doing exactly the same ... Map et all, replacing ${variables} ... time for some cleanup of mine.
    – YoYo
    May 12, 2013 at 19:16
  • To replace for example this: " $#,##0.0 " to this " '$'#,##0.0 " Use Matcher.quoteReplacement(...) So you get: if (replace != null) { String rp = Matcher.quoteReplacement("\'" + replace + "\'"); matcher.appendReplacement(sb, rp); }
    – Hank Moody
    Sep 8, 2017 at 10:33
11

I know this is old, I was myself looking for a, appendReplacement/appendTail example when I found it; However, the OP's question doesn't need those complicated multi-line solutions I saw here.

In this exact case, when the string to replace holds itself the value we want to replace with, then this could be done easily with replaceAll:

String line ="${env1}sojods${env2}${env3}";

System.out.println( line.replaceAll("\\$\\{env([0-9]+)\\}", "$1") );

// Output => 1sojods23

DEMO

When the replacement is random based on some conditions or logic on each match, then you can use appendReplacement/appendTail for example

6

Hopefully you would find this code useful:

    Pattern phone = Pattern.compile("\\$\\{env([0-9]+)\\}");
    String line ="${env1}sojods${env2}${env3}";
    Matcher action = phone.matcher(line);
    StringBuffer sb = new StringBuffer(line.length());
    while (action.find()) {
      String text = action.group(1);
      action.appendReplacement(sb, Matcher.quoteReplacement(text));
    }
    action.appendTail(sb);
    System.out.println(sb.toString());

The output is the expected: 1sojods23.

3
  • how about var name is env_a, env_b and env_c ?
    – Kent
    Mar 7, 2012 at 17:16
  • Ok no prob the pattern of the group can be changed. I am aiming only at the very specific question of the OP, but I guess he can change the pattern accordingly (after all no good specification was given). Mar 7, 2012 at 17:17
  • special Thanks really thanks for your quick answer and it’s really great answer. Mar 7, 2012 at 17:21
5

This gives you 1sojods23:

String s = "${env1}sojods${env2}${env3}";
final Pattern myPattern = Pattern.compile("\\$\\{[^\\}]*\\}");
Matcher m = myPattern.matcher(s);
int i = 0;
while (m.find()) {
    s = m.replaceFirst(String.valueOf(++i));
    m = myPattern.matcher(s);
}

System.out.println(s);

and this works too:

final String re = "\\$\\{[^\\}]*\\}";
String s = "${env1}sojods${env2}${env3}";
int i = 0;
String t;
while (true) {
    t = s.replaceFirst(re, String.valueOf(++i));
    if (s.equals(t)) {
        break;
    } else {
        s = t;
    }
}

System.out.println(s);
0
0

You can use a StringBuffer in combination with the Matcher appendReplacement() method, but if the the pattern does not match, there is no point in creating the StringBuffer.

For example, here is a pattern that matches ${...}. Group 1 is the contents between the braces.

static Pattern rxTemplate = Pattern.compile("\\$\\{([^}\\s]+)\\}");

And here is sample function that uses that pattern.

private static String replaceTemplateString(String text) {
    StringBuffer sb = null;
    Matcher m = rxTemplate.matcher(text);
    while (m.find()) {
        String t = m.group(1);
        t = t.toUpperCase(); // LOOKUP YOUR REPLACEMENT HERE

        if (sb == null) {
            sb = new StringBuffer(text.length());
        }
        m.appendReplacement(sb, t);
    }
    if (sb == null) {
        return text;
    } else {
        m.appendTail(sb);
        return sb.toString();
    }
}
0
    Map<String, String> replacements = new HashMap<String, String>() {
        {
            put("env1", "1");
            put("env2", "2");
            put("env3", "3");

        }
    };

    String line = "${env1}sojods${env2}${env3}";

    String rx = "\\$\\{(.*?)\\}";

    StringBuffer sb = new StringBuffer();
    Pattern p = Pattern.compile(rx);
    Matcher m = p.matcher(line);

    while (m.find()) {
        // Avoids throwing a NullPointerException in the case that you
        // Don't have a replacement defined in the map for the match
        String repString = replacements.get(m.group(1));
        if (repString != null)
            m.appendReplacement(sb, repString);
    }
    m.appendTail(sb);

    System.out.println(sb.toString());

In the above example we can use map with just key and values --keys can be env1 ,env2 ..

-2

Use groups once it is matched ${env1} will be your first group and then you use regex to replace what is in each group.

Pattern p = Pattern.compile("(${\\.})");
Matcher m = p.matcher(line);
while (m.find())
  for (int j = 0; j <= m.groupCount(); j++)
    //here you do replacement - check on the net how to do it;)
1
  • i tried this pattern but get the following exception: Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 1 (${\.}) Mar 7, 2012 at 16:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.