Java regular expressions extract and replace values

Java regular expressions extract and replace values … here is a solution to the problem.

Java regular expressions extract and replace values

Enter a string

${abc.xzy}/demo/${ttt.bbb}
test${kkk.mmm}

Outcome.
World/Demo/Hello
Test the system

The text inside the curly braces is the key for my property. I want to replace these properties with runtime values.

I

can do the following to get a regular expression match, but what should I put in the replacement logic to change ${…} to match the corresponding runtime value in the input string.

Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(s);
while (m.find()) {
   replace logic comes here
}

Solution

Another approach is to use a third-party library, such as Apache Commons Text.
Their StringSubstitutor class looks promising.

Map valuesMap = HashMap();
valuesMap.put("abc.xzy", "World");
valuesMap.put("ttt.bbb", "Hello");
valuesMap.put("kkk.mmm", "System");

String templateString = "${abc.xzy}/demo/${ttt.bbb} test${kkk.mmm}"
StringSubstitutor sub = new StringSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

For more information, check out Javadoc https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html

Related Problems and Solutions