Skip to content

Instantly share code, notes, and snippets.

@stevenschlansker
Created November 15, 2011 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenschlansker/1365649 to your computer and use it in GitHub Desktop.
Save stevenschlansker/1365649 to your computer and use it in GitHub Desktop.
public class ElLikeSubstitutionUtils {
private static final Pattern MATCH_PATTERN = Pattern.compile("\\$\\{([^}]+)\\}");
/**
* Replace ${name} with the appropriate template value retrieved from the map.
* Does not gracefully handle nested or mismatched brace patterns
*/
public static Verified<String> substitute(String string, Map<String, String> parameters) {
List<SyndicationVerificationError> errors = Lists.newArrayList();
Matcher m = MATCH_PATTERN.matcher(string);
StringBuffer result = new StringBuffer();
while (m.find()) {
String parameterName = m.group(1);
String replacement = parameters.get(parameterName);
if (replacement == null) {
replacement = "";
errors.add(new SyndicationVerificationError("Parameter " + parameterName + " not present in map"));
}
m.appendReplacement(result, replacement);
}
m.appendTail(result);
if (!errors.isEmpty()) {
return new VerifiedFailure<String>(errors);
}
return new VerifiedSuccess<String>(result.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment