javastringcharacter-replacement

Replacing names of the variable with value of the variable in a String in Java


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.


Solution

  • 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.