Fun with Regular Expressions: ANT-style variable replacing in strings
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:
propertyA=SomeValue
propertyB=${propertyA}.SomeOtherValue
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);
System.out.println(variable);
}
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);
}
m.appendTail(result);
return result.toString();
}
Regular Expressions do save the day!
Thanks for reading this post. Follow me on twitter here to be notified about updates and other posts I write. Or, subscribe to my RSS feed here
-
http://hkdennis2k.homeip.net/ Dennis
-
http://www.peterfriese.de Peter
-
http://divbyzero.com Nick Boldt
-
http://divbyzero.com Nick Boldt
-
http://www.peterfriese.de Peter
-
http://pulse.yahoo.com/_BV652BCV4OQAXFNLPUBL4A32B4 Honey Jane


