Top Description Inners Fields Constructors Methods
org.apache.commons.text

public Class StringSubstitutor

extends Object
Class Inheritance
Imports
java.util.ArrayList, .List, .Map, .Objects, .Properties, java.util.function.Function, java.util.stream.Collectors, org.apache.commons.lang3.Validate, org.apache.commons.text.lookup.StringLookup, .StringLookupFactory, org.apache.commons.text.matcher.StringMatcher, .StringMatcherFactory

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.

Using System Properties

The simplest example is to use this class to replace Java System properties. For example:

StringSubstitutor
    .replaceSystemProperties("You are running with java.version = ${java.version} and os.name = ${os.name}.");

Using a Custom Map

Typical usage of this class follows the following pattern:

For example:

// Build map
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";

// Build StringSubstitutor
StringSubstitutor sub = new StringSubstitutor(valuesMap);

// Replace
String resolvedString = sub.replace(templateString);

yielding:

"The quick brown fox jumped over the lazy dog."

Providing Default Values

You can set a default value for unresolved variables. The default value for a variable can be appended to the variable name after the variable default value delimiter. The default value of the variable default value delimiter is ":-", as in bash and other *nix shells.

You can set the variable value delimiter with setValueDelimiterMatcher(StringMatcher), setValueDelimiter(char) or setValueDelimiter(String).

For example:

// Build map
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target} ${undefined.number:-1234567890} times.";

// Build StringSubstitutor
StringSubstitutor sub = new StringSubstitutor(valuesMap);

// Replace
String resolvedString = sub.replace(templateString);

yielding:

"The quick brown fox jumped over the lazy dog 1234567890 times."

StringSubstitutor supports throwing exceptions for unresolved variables, you enable this by setting calling setEnableUndefinedVariableException(boolean) with true.

Reusing Instances

Static shortcut methods cover the most common use cases. If multiple replace operations are to be performed, creating and reusing an instance of this class will be more efficient.

Using Interpolation

The default interpolator lets you use string lookups like:

final StringSubstitutor interpolator = StringSubstitutor.createInterpolator();
final String text = interpolator.replace(
      "Base64 Decoder:        ${base64Decoder:SGVsbG9Xb3JsZCE=}\n"
    + "Base64 Encoder:        ${base64Encoder:HelloWorld!}\n"
    + "Java Constant:         ${const:java.awt.event.KeyEvent.VK_ESCAPE}\n"
    + "Date:                  ${date:yyyy-MM-dd}\n"
    + "Environment Variable:  ${env:USERNAME}\n"
    + "File Content:          ${file:UTF-8:src/test/resources/document.properties}\n"
    + "Java:                  ${java:version}\n"
    + "Localhost:             ${localhost:canonical-name}\n"
    + "Properties File:       ${properties:src/test/resources/document.properties::mykey}\n"
    + "Resource Bundle:       ${resourceBundle:org.apache.commons.text.example.testResourceBundleLookup:mykey}\n"
    + "System Property:       ${sys:user.dir}\n"
    + "URL Decoder:           ${urlDecoder:Hello%20World%21}\n"
    + "URL Encoder:           ${urlEncoder:Hello World!}\n"
    + "XML XPath:             ${xml:src/test/resources/document.xml:/root/path/to/node}\n");

For documentation and a full list of available lookups, see StringLookupFactory.

Note

The list of lookups available by default in createInterpolator() changed in version 1.10.0. See the StringLookupFactory documentation for details and an explanation on how to reproduce the previous functionality.

Using Recursive Variable Replacement

Variable replacement can work recursively by calling setEnableSubstitutionInVariables(boolean) with true. If a variable value contains a variable then that variable will also be replaced. Cyclic replacements are detected and will throw an exception.

You can get the replace result to contain a variable prefix. For example:

"The variable ${${name}} must be used."

If the value of the "name" variable is "x", then only the variable "name" is replaced resulting in:

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

In some complex scenarios you might even want to perform substitution in the names of variables, for instance

${jre-${java.specification.version}}

StringSubstitutor supports this recursive substitution in variable names, but it has to be enabled explicitly by calling setEnableSubstitutionInVariables(boolean) with true.

Thread Safety

This class is not thread safe.

Since
1.3

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
StringSubstitutor.Result

The low-level result of a substitution.

Field Summary

Modifier and TypeField and Description
public static final char
DEFAULT_ESCAPE

Constant for the default escape character.

public static final StringMatcher
DEFAULT_PREFIX

Constant for the default variable prefix.

public static final StringMatcher
DEFAULT_SUFFIX

Constant for the default variable suffix.

public static final StringMatcher
DEFAULT_VALUE_DELIMITER

Constant for the default value delimiter of a variable.

public static final String
DEFAULT_VAR_DEFAULT

The default variable default separator.

public static final String
DEFAULT_VAR_END

The default variable end separator.

public static final String
DEFAULT_VAR_START

The default variable start separator.

private boolean
disableSubstitutionInValues

The flag whether substitution in variable values is disabled.

private boolean
enableSubstitutionInVariables

The flag whether substitution in variable names is enabled.

private char
escapeChar

Stores the escape character.

private boolean
failOnUndefinedVariable

The flag whether exception should be thrown on undefined variable.

private StringMatcher
prefixMatcher

Stores the variable prefix.

private boolean
preserveEscapes

Whether escapes should be preserved.

private StringMatcher
suffixMatcher

Stores the variable suffix.

private StringMatcher
valueDelimiterMatcher

Stores the default variable value delimiter.

private StringLookup
variableResolver

Variable resolution is delegated to an implementor of StringLookup.

Constructor Summary

AccessConstructor and Description
public
StringSubstitutor()

Constructs a new instance with defaults for variable prefix and suffix and the escaping character.

public <
the type of the values in the map.
V
>
StringSubstitutor(final Map<String, V>
the map with the variables' values, may be null.
valueMap
)

Constructs a new initialized instance.

public <
the type of the values in the map.
V
>
StringSubstitutor(final Map<String, V>
the map with the variables' values, may be null.
valueMap
,
final String
the prefix for variables, not null.
prefix
,
final String
the suffix for variables, not null.
suffix
)

Constructs a new initialized instance.

public <
the type of the values in the map.
V
>
StringSubstitutor(final Map<String, V>
the map with the variables' values, may be null.
valueMap
,
final String
the prefix for variables, not null.
prefix
,
final String
the suffix for variables, not null.
suffix
,
final char
the escape character.
escape
)

Constructs a new initialized instance.

public <
the type of the values in the map.
V
>
StringSubstitutor(final Map<String, V>
the map with the variables' values, may be null.
valueMap
,
final String
the prefix for variables, not null.
prefix
,
final String
the suffix for variables, not null.
suffix
,
final char
the escape character.
escape
,
final String
the variable default value delimiter, may be null.
valueDelimiter
)

Constructs a new initialized instance.

public
StringSubstitutor(final StringLookup
the variable resolver, may be null
variableResolver
)

Constructs a new initialized instance.

public
StringSubstitutor(final StringLookup
the variable resolver, may be null.
variableResolver
,
final String
the prefix for variables, not null.
prefix
,
final String
the suffix for variables, not null.
suffix
,
final char
the escape character.
escape
)

Constructs a new initialized instance.

public
StringSubstitutor(final StringLookup
the variable resolver, may be null.
variableResolver
,
final String
the prefix for variables, not null.
prefix
,
final String
the suffix for variables, not null.
suffix
,
final char
the escape character.
escape
,
final String
the variable default value delimiter string, may be null.
valueDelimiter
)

Constructs a new initialized instance.

public
StringSubstitutor(final StringLookup
the variable resolver, may be null
variableResolver
,
final StringMatcher
the prefix for variables, not null.
prefixMatcher
,
final StringMatcher
the suffix for variables, not null.
suffixMatcher
,
final char
the escape character.
escape
)

Constructs a new initialized instance.

public
StringSubstitutor(final StringLookup
the variable resolver, may be null
variableResolver
,
final StringMatcher
the prefix for variables, not null
prefixMatcher
,
final StringMatcher
the suffix for variables, not null
suffixMatcher
,
final char
the escape character
escape
,
final StringMatcher
the variable default value delimiter matcher, may be null
valueDelimiterMatcher
)

Constructs a new initialized instance.

public
StringSubstitutor(final StringSubstitutor
The StringSubstitutor used as the source.
other
)

Creates a new instance based on the given.

Method Summary

Modifier and TypeMethod and Description
private void
checkCyclicSubstitution(final String
the variable name to check
varName
,
final List<String>
the list of prior variables
priorVariables
)

Checks if the specified variable is already in the stack (list) of variables.

public static StringSubstitutor

Returns:

a new instance using the interpolator string lookup.
createInterpolator
()

Creates a new instance using the interpolator string lookup StringLookupFactory#interpolatorStringLookup().

public char

Returns:

The character used for escaping variable references.
getEscapeChar
()

Returns the escape character.

public StringLookup

Returns:

The StringLookup.
getStringLookup
()

Gets the StringLookup that is used to lookup variables.

public StringMatcher

Returns:

The variable default value delimiter matcher in use, may be null.
getValueDelimiterMatcher
()

Gets the variable default value delimiter matcher currently in use.

public StringMatcher

Returns:

The prefix matcher in use
getVariablePrefixMatcher
()

Gets the variable prefix matcher currently in use.

public StringMatcher

Returns:

The suffix matcher in use
getVariableSuffixMatcher
()

Gets the variable suffix matcher currently in use.

public boolean

Returns:

The substitution in variable values flag.
isDisableSubstitutionInValues
()

Returns a flag whether substitution is disabled in variable values.If set to true, the values of variables can contain other variables will not be processed and substituted original variable is evaluated, e.g.

Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("name", "Douglas ${surname}");
valuesMap.put("surname", "Crockford");
String templateString = "Hi ${name}";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
public boolean

Returns:

The substitution in variable names flag.
isEnableSubstitutionInVariables
()

Returns a flag whether substitution is done in variable names.

public boolean

Returns:

The fail on undefined variable flag.
isEnableUndefinedVariableException
()

Returns a flag whether exception can be thrown upon undefined variable.

public boolean

Returns:

The preserve escape flag.
isPreserveEscapes
()

Returns the flag controlling whether escapes are preserved during substitution.

public static <
the type of the values in the map
V
>
String

Returns:

The result of the replace operation
replace
(final Object
the source text containing the variables to substitute, null returns null
source
,
final Map<String, V>
the map with the values, may be null
valueMap
)

Replaces all the occurrences of variables in the given source object with their matching values from the map.

public static <
the type of the values in the map
V
>
String

Returns:

The result of the replace operation
replace
(final Object
the source text containing the variables to substitute, null returns null
source
,
final Map<String, V>
the map with the values, may be null
valueMap
,
final String
the prefix of variables, not null
prefix
,
final String
the suffix of variables, not null
suffix
)

Replaces all the occurrences of variables in the given source object with their matching values from the map.

public static String

Returns:

The result of the replace operation
replace
(final Object
the source text containing the variables to substitute, null returns null
source
,
final Properties
the properties with values, may be null
valueProperties
)

Replaces all the occurrences of variables in the given source object with their matching values from the properties.

public String

Returns:

The result of the replace operation.
replace
(final char[]
the character array to replace in, not altered, null returns null.
source
)

Replaces all the occurrences of variables with their matching values from the resolver using the given source array as a template.

public String

Returns:

The result of the replace operation.
replace
(final char[]
the character array to replace in, not altered, null returns null.
source
,
final int
the start offset within the array, must be valid.
offset
,
final int
the length within the array to be processed, must be valid.
length
)

Replaces all the occurrences of variables with their matching values from the resolver using the given source array as a template.

public String

Returns:

The result of the replace operation.
replace
(final CharSequence
the buffer to use as a template, not changed, null returns null.
source
)

Replaces all the occurrences of variables with their matching values from the resolver using the given source as a template.

public String

Returns:

The result of the replace operation.
replace
(final CharSequence
the buffer to use as a template, not changed, null returns null.
source
,
final int
the start offset within the array, must be valid.
offset
,
final int
the length within the array to be processed, must be valid.
length
)

Replaces all the occurrences of variables with their matching values from the resolver using the given source as a template.

public String

Returns:

The result of the replace operation.
replace
(final Object
the source to replace in, null returns null.
source
)

Replaces all the occurrences of variables in the given source object with their matching values from the resolver.

public String

Returns:

The result of the replace operation.
replace
(final String
the string to replace in, null returns null.
source
)

Replaces all the occurrences of variables with their matching values from the resolver using the given source string as a template.

public String

Returns:

The result of the replace operation.
replace
(final String
the string to replace in, null returns null.
source
,
final int
the start offset within the source, must be valid.
offset
,
final int
the length within the source to be processed, must be valid.
length
)

Replaces all the occurrences of variables with their matching values from the resolver using the given source string as a template.

public String

Returns:

The result of the replace operation.
replace
(final StringBuffer
the buffer to use as a template, not changed, null returns null.
source
)

Replaces all the occurrences of variables with their matching values from the resolver using the given source buffer as a template.

public String

Returns:

The result of the replace operation.
replace
(final StringBuffer
the buffer to use as a template, not changed, null returns null.
source
,
final int
the start offset within the source, must be valid.
offset
,
final int
the length within the source to be processed, must be valid.
length
)

Replaces all the occurrences of variables with their matching values from the resolver using the given source buffer as a template.

public String

Returns:

The result of the replace operation.
replace
(final TextStringBuilder
the builder to use as a template, not changed, null returns null.
source
)
References Deprecated TextStringBuilder is deprecated or references (maybe indirectly) at least one deprecated element.

Replaces all the occurrences of variables with their matching values from the resolver using the given source builder as a template.

public String

Returns:

The result of the replace operation.
replace
(final TextStringBuilder
the builder to use as a template, not changed, null returns null.
source
,
final int
the start offset within the source, must be valid.
offset
,
final int
the length within the source to be processed, must be valid.
length
)
References Deprecated TextStringBuilder is deprecated or references (maybe indirectly) at least one deprecated element.

Replaces all the occurrences of variables with their matching values from the resolver using the given source builder as a template.

public boolean

Returns:

true if altered
replaceIn
(final StringBuffer
the buffer to replace in, updated, null returns zero.
source
)

Replaces all the occurrences of variables within the given source buffer with their matching values from the resolver.

public boolean

Returns:

true if altered.
replaceIn
(final StringBuffer
the buffer to replace in, updated, null returns zero.
source
,
final int
the start offset within the source, must be valid.
offset
,
final int
the length within the source to be processed, must be valid.
length
)

Replaces all the occurrences of variables within the given source buffer with their matching values from the resolver.

public boolean

Returns:

true if altered.
replaceIn
(final StringBuilder
the buffer to replace in, updated, null returns zero.
source
)

Replaces all the occurrences of variables within the given source buffer with their matching values from the resolver.

public boolean

Returns:

true if altered.
replaceIn
(final StringBuilder
the buffer to replace in, updated, null returns zero.
source
,
final int
the start offset within the source, must be valid.
offset
,
final int
the length within the source to be processed, must be valid.
length
)

Replaces all the occurrences of variables within the given source builder with their matching values from the resolver.

public boolean

Returns:

true if altered.
replaceIn
(final TextStringBuilder
the builder to replace in, updated, null returns zero.
source
)
References Deprecated TextStringBuilder is deprecated or references (maybe indirectly) at least one deprecated element.

Replaces all the occurrences of variables within the given source builder with their matching values from the resolver.

public boolean

Returns:

true if altered.
replaceIn
(final TextStringBuilder
the builder to replace in, null returns zero.
source
,
final int
the start offset within the source, must be valid.
offset
,
final int
the length within the source to be processed, must be valid.
length
)
References Deprecated TextStringBuilder is deprecated or references (maybe indirectly) at least one deprecated element.

Replaces all the occurrences of variables within the given source builder with their matching values from the resolver.

public static String

Returns:

The result of the replace operation
replaceSystemProperties
(final Object
the source text containing the variables to substitute, null returns null
source
)

Replaces all the occurrences of variables in the given source object with their matching values from the system properties.

protected String

Returns:

The variable's value or null if the variable is unknown.
resolveVariable
(final String
the name of the variable, not null.
variableName
,
final TextStringBuilder
the buffer where the substitution is occurring, not null.
buf
,
final int
the start position of the variable including the prefix, valid.
startPos
,
final int
the end position of the variable including the suffix, valid.
endPos
)
References Deprecated TextStringBuilder is deprecated or references (maybe indirectly) at least one deprecated element.

Internal method that resolves the value of a variable.

public StringSubstitutor

Returns:

this instance.
setDisableSubstitutionInValues
(final boolean
true if substitution in variable value are disabled.
disableSubstitutionInValues
)

Sets a flag whether substitution is done in variable values (recursive).

public StringSubstitutor

Returns:

this instance.
setEnableSubstitutionInVariables
(final boolean
the new value of the flag.
enableSubstitutionInVariables
)

Sets a flag whether substitution is done in variable names.

public StringSubstitutor

Returns:

this instance.
setEnableUndefinedVariableException
(final boolean
true if exception should be thrown on undefined variable.
failOnUndefinedVariable
)

Sets a flag whether exception should be thrown if any variable is undefined.

public StringSubstitutor

Returns:

this instance.
setEscapeChar
(final char
the escape character (0 for disabling escaping).
escapeChar
)

Sets the escape character.

public StringSubstitutor

Returns:

this instance.
setPreserveEscapes
(final boolean
true if escapes are to be preserved.
preserveEscapes
)

Sets a flag controlling whether escapes are preserved during substitution.

public StringSubstitutor

Returns:

this instance.
setValueDelimiter
(final char
the variable default value delimiter character to use.
valueDelimiter
)

Sets the variable default value delimiter to use.

public StringSubstitutor

Returns:

this instance.
setValueDelimiter
(final String
the variable default value delimiter string to use, may be null or empty.
valueDelimiter
)

Sets the variable default value delimiter to use.

public StringSubstitutor

Returns:

this instance.
setValueDelimiterMatcher
(final StringMatcher
variable default value delimiter matcher to use, may be null.
valueDelimiterMatcher
)

Sets the variable default value delimiter matcher to use.

public StringSubstitutor

Returns:

this instance.
setVariablePrefix
(final char
the prefix character to use.
prefix
)

Sets the variable prefix to use.

public StringSubstitutor

Returns:

this instance.
setVariablePrefix
(final String
the prefix for variables, not null.
prefix
)

Sets the variable prefix to use.

public StringSubstitutor

Returns:

this instance.
setVariablePrefixMatcher
(final StringMatcher
the prefix matcher to use, null ignored.
prefixMatcher
)

Sets the variable prefix matcher currently in use.

public StringSubstitutor

Returns:

this instance.
setVariableResolver
(final StringLookup
the VariableResolver.
variableResolver
)

Sets the VariableResolver that is used to lookup variables.

public StringSubstitutor

Returns:

this instance.
setVariableSuffix
(final char
the suffix character to use.
suffix
)

Sets the variable suffix to use.

public StringSubstitutor

Returns:

this instance.
setVariableSuffix
(final String
the suffix for variables, not null.
suffix
)

Sets the variable suffix to use.

public StringSubstitutor

Returns:

this instance.
setVariableSuffixMatcher
(final StringMatcher
the suffix matcher to use, null ignored.
suffixMatcher
)

Sets the variable suffix matcher currently in use.

protected boolean

Returns:

true if altered.
substitute
(final TextStringBuilder
the string builder to substitute into, not null.
builder
,
final int
the start offset within the builder, must be valid.
offset
,
final int
the length within the builder to be processed, must be valid.
length
)
References Deprecated TextStringBuilder is deprecated or references (maybe indirectly) at least one deprecated element.

Internal method that substitutes the variables.

private StringSubstitutor.Result

Returns:

The result.
substitute
(final TextStringBuilder
the string builder to substitute into, not null.
builder
,
final int
the start offset within the builder, must be valid.
offset
,
final int
the length within the builder to be processed, must be valid.
length
,
List<String>
the stack keeping track of the replaced variables, may be null.
priorVariables
)
References Deprecated TextStringBuilder is deprecated or references (maybe indirectly) at least one deprecated element.

Recursive handler for multiple levels of interpolation.

public String

Returns:

a string representation of the object.
toString
()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait