给出一个像这样的字符串:
Hello {FIRST_NAME},this is a personalized message for you.
其中FIRST_NAME是任意令牌(传递给方法的地图中的一个键),要编写一个将该字符串变为:
Hello Jim,this is a personalized message for you.
给出了一个带有条目FIRST_NAME的地图 – >吉姆.
看起来StringTokenizer是最直接的方法,但Javadocs真的说你应该更喜欢使用正则表达式.您将如何在基于正则表达式的解决方案中执行此操作?
解决方法
尝试这个:
注意:author’s final solution建立在这个样本之上,更简洁.
public class TokenReplacer { private Pattern tokenPattern; public TokenReplacer() { tokenPattern = Pattern.compile("\\{([^}]+)\\}"); } public String replaceTokens(String text,Map<String,String> valuesByKey) { StringBuilder output = new StringBuilder(); Matcher tokenMatcher = tokenPattern.matcher(text); int cursor = 0; while (tokenMatcher.find()) { // A token is defined as a sequence of the format "{...}". // A key is defined as the content between the brackets. int tokenStart = tokenMatcher.start(); int tokenEnd = tokenMatcher.end(); int keyStart = tokenMatcher.start(1); int keyEnd = tokenMatcher.end(1); output.append(text.substring(cursor,tokenStart)); String token = text.substring(tokenStart,tokenEnd); String key = text.substring(keyStart,keyEnd); if (valuesByKey.containsKey(key)) { String value = valuesByKey.get(key); output.append(value); } else { output.append(token); } cursor = tokenEnd; } output.append(text.substring(cursor)); return output.toString(); } }