I'm using regex to replace placeholders in a template file.
I have this method:
public static String processTemplate(String template, Map<String, String> attributes) {
Matcher m = PLACEHOLDER_PATTERN.matcher(template);
String message = template;
boolean matches = m.matches();
if (matches) {
for (int i = 1; i < m.groupCount() + 1; i++) {
message = message.replaceAll(m.group(i), attributes.get(m.group(i)));
}
}
return message;
}
with this pattern:
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("(\\$\\{.*?})");
But this test fails:
@Test
public void templates() {
Map<String, String> attributes = new HashMap<>();
attributes.put("${wobble}", "wobble");
String result = processTemplate("wibble ${wobble}", attributes);
assertEquals("wibble wobble", result);
}
And I don't know why. It seems that the 'match' is returning false.
^nor$in the pattern, thePattern.MULTILINEwill not have any effect on your pattern. ThePattern.DOTALLwill force.match newline symbols, and you have.in the pattern.