Over a million developers have joined DZone.
Silver Partner

Fun with Regular Expressions: ANT-style Variable Replacing in Strings

· Java Zone

I recently felt the need to write a piece of code that resolves ANT-style variables in a string. Suppose you have a property file similar to this one:

listofThings=${propertyA}, ${propertyB}, constantValue

Let's further assume you want to read property listofThings, and resolve the variables. Isn't that a perfect job for regular expressions?

Using Regex Tester, I came up with the following regular expression to find occurrence of ${variable}:


Using java.util.regex.Pattern and java.util.regex.Matcher to find all occurrences is rather trivial:

Pattern re = Pattern.compile("\\$\\{(.+?)\\}");
Matcher m = re.matcher(sourcestring);
while (m.find()) {
  String variable = m.group(1);

Replacing the variables with their concrete values is not so trivial. You might be tempted to use String.substring():

value = sourcestring.substring(0, m.start()) + replacement + (sourcestring.substring(m.end()));

But this will modify the source string, basically throwing the matcher out of the curve.

Looking at the matcher API, I found java.util.regex.Matcher.appendReplacement(StringBuffer, String) and java.util.regex.Matcher.appendTail(StringBuffer). These two little gems to the trick:

private String resolve(String sourcestring, Properties props) {
  Pattern re = Pattern.compile("\\$\\{(.+?)\\}");
  Matcher m = re.matcher(sourcestring);
  StringBuffer result = new StringBuffer();
  while (m.find()) {
    String variable = m.group(1);
    String resolved = resolve(props.getProperty(variable), props);
    m.appendReplacement(result, resolved);
  return result.toString();

Regular Expressions do save the day!

From http://www.peterfriese.de


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}