Fun with Regular Expressions: ANT-style Variable Replacing in Strings
Join the DZone community and get the full member experience.
Join For Freei 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!
Opinions expressed by DZone contributors are their own.
Comments