基本上你想像这样复制Matcher.replaceAll()的执行:
public static String replaceTags(String message, Map<String, String> tags) {
Pattern p = Pattern.compile("#(\\w+)#");
Matcher m = p.matcher(message);
boolean result = m.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
m.appendReplacement(sb, tags.containsKey(m.group(1) ? tags.get(m.group(1)) : "");
result = m.find();
} while (result);
m.appendTail(sb);
message = sb.toString();
}
return message;
}
Note: I've made an assumption about the valid tag (namely \w in the regex). You will need to cater this for what's really valid (eg "#([\w_]+)#").
I've also assumed the tags above looks something like:
Map<String, String> tags = new HashMap<String, String>();
tags.add("firstName", "Skippy");
and not:
tags.add("#firstName#", "Skippy");
If the second is correct you'll need to adjust accordingly.
This method makes exactly one pass across the message string so it doesn't get much more efficient than this.