2

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?

Sayan Bhattacharya
  • 1,365
  • 1
  • 4
  • 14
MrNobody
  • 535
  • 8
  • 24

2 Answers2

4

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 "
Idan Elhalwani
  • 538
  • 4
  • 12
2

If you want to set default value for all variables, you can construct StringSubstitutor with StringLookup, where the StringLookup just wrap the parameter map and use getOrDefault to provide your default value.


import org.apache.commons.text.StringSubstitutor;
import org.apache.commons.text.lookup.StringLookup;

import java.util.HashMap;
import java.util.Map;

public class SubstituteWithDefault {
    public static void main(String[] args) {
        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(new StringLookup() {
            @Override
            public String lookup(String s) {
                return textParameters.getOrDefault(s, "").toString();
            }
        });
        String replacedText = substitutor.replace(myText);
        System.out.println(replacedText);
    }
}
samabcde
  • 6,988
  • 2
  • 25
  • 41