0

I have a String like this: "#{var1} is like #{var2}.
I would like to replace the "#{var1} and "#{var1} with the values of variables var1 and var1. Is there a smart way to do this without iterating over the whole string and finding the pattern #{} and then replacing it?
I couldn't find a library that would do that.

3

4 Answers 4

3

You can use a the java buildin regular expression mechanism to find the pattern in the inspected string and make the replacement using the proper functions. Let me show you...

 public static void main(String[] args)
    {
      StringBuilder output = new StringBuilder();
      String inputString = "sequence to analize #{var1} is like #{var2}";
      Pattern pattern = Pattern.compile("#\\{(.*?)\\}");
      Matcher matcher = pattern.matcher(inputString);
      int lastStart = 0;
      while (matcher.find()) {
        String subString = inputString.substring(lastStart,matcher.start());
        String varName = matcher.group(1);
        String replacement = getVarValue (varName);
        output.append(subString).append(replacement);
        lastStart = matcher.end();
      }
      System.out.println(output.toString());
    }

    private static String getVarValue(String varName) {
       return "value"; // do what you got to replace the variable name for its value
    }

Perhaps the example needs to be worked a little more.. but it can give you an idea.

Hope it Helps.

Greetings.

Sign up to request clarification or add additional context in comments.

1 Comment

Must add more line output.append(inputString.substring(lastStart)); after the while loop.
2

You can do something like this. Using String.format. It is not really pretty but works. It does not use the variable name but still extremely useful.

String string = String.format("A String %s %2d", aStringVar, anIntVar);

Some more examples here

Hope this helps.

Comments

1

Probably the easiest way to achieve this is using String.format. It internally uses the Formatter class.

This approach has the beauty you don't need any third party library (String.format was introduced with Java 1.5).

Here a complete example:

import static java.lang.String.format;

public class Interpolate {
    public static void main(String[] args) {
        String var1 = "foo";
        String var2 = "bar";
        String s = format("%1$s is like %2$s is like %1$s",var1, var2);
        System.out.println(s); // "foo is like bar is like foo"
    }
}

Notice the numbers in %1$s or %2$s. They refer to the position of the parameters in the format call. This allows you to use the variable multiple times and you can rearrange the order of the variables freely (within the format string).

For more info on the format string see the Formatter documentation.

Comments

0

You can consider using StringSubstitutor from Apache Commons Text. Maven repo link.

The template variable syntax is ${variableName}. Example:

Map<String> variables = Map.of(
  "firstName", "John",
  "lastName", "Doe");

String template = "Welcome ${firstName} ${lastName}!";

String resolved = new StringSubstitutor(variables).replace(template);

log.info(resolved); // Welcome John Doe!

If you are on Java 21, you can consider String Templates for a "native" approach.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.