Here you can find the source of replace(String original, CharSequence target, CharSequence replacement)
private static final String replace(String original, CharSequence target, CharSequence replacement)
//package com.java2s; //License from project: Apache License import java.util.regex.Pattern; public class Main { /**/* w ww . ja va 2 s.c o m*/ * Implementation according to JDK5 String.replace(CharSequence,CharSequence) */ private static final String replace(String original, CharSequence target, CharSequence replacement) { return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(original) .replaceAll(quoteReplacement(replacement.toString())); } /** * Implementation according to JDK5 String.replace(CharSequence,CharSequence) */ private static String quoteReplacement(String s) { if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) { return s; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '\\') { sb.append('\\'); sb.append('\\'); } else if (c == '$') { sb.append('\\'); sb.append('$'); } else { sb.append(c); } } return sb.toString(); } }