Substitutes variables within a string by values.
This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}
. The prefix and suffix can be changed via constructors and set methods.
Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.
The simplest example is to use this class to replace Java System properties. For example:
StrSubstitutor.replaceSystemProperties( "You are running with java.version = ${java.version} and os.name = ${os.name}.");
Typical usage of this class follows the following pattern: First an instance is created and initialized with the map that contains the values for the available variables. If a prefix and/or suffix for variables should be used other than the default ones, the appropriate settings can be performed. After that the replace()
method can be called passing in the source text for interpolation. In the returned text all variable references (as long as their values are known) will be resolved. The following example demonstrates this:
Map valuesMap = HashMap(); valuesMap.put("animal", "quick brown fox"); valuesMap.put("target", "lazy dog"); String templateString = "The ${animal} jumped over the ${target}."; StrSubstitutor sub = new StrSubstitutor(valuesMap); String resolvedString = sub.replace(templateString);
yielding:
The quick brown fox jumped over the lazy dog.
In addition to this usage pattern there are some static convenience methods that cover the most common use cases. These methods can be used without the need of manually creating an instance. However if multiple replace operations are to be performed, creating and reusing an instance of this class will be more efficient.
Variable replacement works in a recursive way. Thus, if a variable value contains a variable then that variable will also be replaced. Cyclic replacements are detected and will cause an exception to be thrown.
Sometimes the interpolation's result must contain a variable prefix. As an example take the following source text:
The variable ${${name}} must be used.
Here only the variable's name refered to in the text should be replaced resulting in the text (assuming that the value of the
name
variable is
x
):
The variable ${x} must be used.
To achieve this effect there are two possibilities: Either set a different prefix and suffix for variables which do not conflict with the result text you want to produce. The other possibility is to use the escape character, by default '$'. If this character is placed before a variable reference, this reference is ignored and won't be replaced. For example:
The variable $${${name}} must be used.
@author Apache Software Foundation
@author Oliver Heger
@version $Id: StrSubstitutor.java 902944 2010-01-25 19:32:08Z sebb $
@since 2.2