最有效的方法是使用匹配器连续查找表达式并替换它们,然后将文本附加到字符串生成器中:
Pattern pattern = Pattern.compile("\[(.+?)\]");Matcher matcher = pattern.matcher(text);HashMap<String,String> replacements = new HashMap<String,String>();//populate the replacements map ...StringBuilder builder = new StringBuilder();int i = 0;while (matcher.find()) { String replacement = replacements.get(matcher.group(1)); builder.append(text.substring(i, matcher.start())); if (replacement == null) builder.append(matcher.group(0)); else builder.append(replacement); i = matcher.end();}builder.append(text.substring(i, text.length()));return builder.toString();
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)