javaapache-commonsstring-substitution

Apache StringSubstitutor - Replace not matching variables with empty string


Precondition

I have a string which looks like this: String myText= "This is a foo text containing ${firstParameter} and ${secondParameter}"

And the code looks like this:

Map<String, Object> textParameters=new Hashmap<String,String>();
textParameters.put("firstParameter", "Hello World");
StringSubstitutor substitutor = new StringSubstitutor(textParameters);
String replacedText = substitutor.replace(myText)

The replacedText will be: This is a foo text containing Hello World and ${secondParameter}

The problem

In the replaced string the secondParameter parameter was not provided so for this reason the declaration was printed out.

What I want to achieve?

If a parameter is not mapped then I want to hide its declaration by replacing it with an empty string.

In the example I want to achieve this: This is a foo text containing Hello World and

Question

How can I achieve the mentioned result with StringUtils/Stringbuilder? Should I use regex instead?


Solution

  • You can achieve this by supplying your placeholder with a default value by appending :- to it. (For example ${secondParameter:-my default value}).

    In your case, you can also leave it empty to hide the placeholder if the key is not set.

    String myText = "This is a foo text containing ${firstParameter} and ${secondParameter:-}";
    Map<String, Object> textParameters = new HashMap<>();
    textParameters.put("firstParameter", "Hello World");
    StringSubstitutor substitutor = new StringSubstitutor(textParameters);
    String replacedText = substitutor.replace(myText);
    System.out.println(replacedText);
    // Prints "This is a foo text containing Hello World and "