Discuss / Java / 三种实现,个人喜欢第二种

三种实现,个人喜欢第二种

Topic source

public String render1(Map<String, Object> data) {

		Matcher m = pattern.matcher(template);

		// TODO:

		String result = template;

		while (m.find()) {

			 String sub = template.substring(m.start()+2, m.end()-1);

			 String regex_sub = "\\$\\{"+sub+"\\}";

			 result=result.replaceAll(regex_sub,(String) data.get(sub));

			 System.out.println(result);

		}

		return result;

	}




public String render2(Map<String, Object> data) {

		Matcher m = pattern.matcher(template);

		// TODO:

		StringBuffer result = new StringBuffer();

		int start=0;

		while (m.find()) {

			 String sub = template.substring(m.start()+2, m.end()-1);

			 result.append(template.substring(start,m.start()));

			 result.append(data.get(sub));

			 start=m.end();

		}

		result.append(template.substring(start,template.length()));

		return result.toString();

	}




public String render3(Map<String, Object> data) {

		Matcher m = pattern.matcher(template);

		// TODO:

		StringBuffer result = new StringBuffer();



		while (m.find()) {

			 String sub = template.substring(m.start()+2, m.end()-1);

			  m.appendReplacement(result,(String) data.get(sub));

		}

         m.appendTail(result);

		return result.toString();

	}




  • 1

Reply