Class VariableReplacer

java.lang.Object
de.aristaflow.adept2.util.VariableReplacer

public class VariableReplacer extends Object
Tool class to find and replace variables of the form ${variable}. Example code:
 VariableReplacer varrep = new VariableReplacer("a ${var} string");
 while (varrep.findNext())
 {
   ...
   String var = varrep.getVariable();
   ...
   varrep.replaceWith("short");
   ...
 }
 varrep.getResult()
 
Author:
Patrick Schmidt
  • Field Details

    • VAR_PATTERN

      public static final Pattern VAR_PATTERN
      the regular expression pattern used to find the variables
  • Constructor Details

    • VariableReplacer

      public VariableReplacer(String string)
      Constructs a new VariableReplacer.
      Parameters:
      string - the string to be parsed
  • Method Details

    • findNext

      public boolean findNext()
      Finds the next variable.
      Returns:
      if a next variable was found
    • getVariable

      public String getVariable()
      Returns the current variable name. May be called after findNext() has returned true.
      Returns:
      the current variable name
    • replaceWith

      public void replaceWith(String value)
      Replace the current variable with the given value. Calling this method is optional, i.e. not every variable must be replaced.
      Parameters:
      value - the value to replace the current variable with
    • getResult

      public String getResult()
      Returns the string after replacing the variables.
      Returns:
      the string after replacing the variables
    • replace

      public static String replace(String string, Map<String,String> values)
      Replaces all variables with the values provided in the map. Missing values will be ignored.
      Parameters:
      string - the string containing the variables
      values - the values to replace the variables with
      Returns:
      the result of the replacement
    • replace

      public static String replace(String string, Map<String,String> values, boolean exceptionOnMissing)
      Replaces all variables with the values provided in the map. Missing values can optionally be ignored or lead to an exception.
      Parameters:
      string - the string containing the variables
      values - the values to replace the variables with
      exceptionOnMissing - whether a missing value for a variable should lead to an exception
      Returns:
      the result of the replacement
      Throws:
      MissingResourceException - if exceptionOnMissing is true and the value for an encountered variable is missing from the map