Here you can find the source of replace(String source, String search, String replacement)
public static String replace(String source, String search, String replacement)
//package com.java2s; /*//from ww w . j a v a2 s . co m * $Id: StringUtilities.java,v 1.6 2004/11/03 17:25:52 edankert Exp $ * * Copyright (C) 2002-2004, Cladonia Ltd. All rights reserved. * * This software is the proprietary information of Cladonia Ltd. * Use is subject to license terms. */ import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static String replace(String source, String search, String replacement) { System.out.println("replace( " + source + ", " + search + ", " + replacement + ")"); String result = null; search = "\\Q" + prepareNonRegularExpression(search) + "\\E"; replacement = prepareNonRegularExpressionReplacement(replacement); Pattern pattern = Pattern.compile(search, Pattern.CASE_INSENSITIVE); try { Matcher matcher = pattern.matcher(source); result = matcher.replaceAll(replacement); } catch (Exception e) { e.printStackTrace(); } return result; } public static String prepareNonRegularExpression(String regexp) { StringBuffer result = new StringBuffer(regexp); int index = result.indexOf("\\E"); while (index != -1) { result.replace(index, index + 2, "\\E\\\\E\\Q"); index = result.indexOf("\\E", index + 7); } // Last character is a '\', make sure to escape otherwise it will escape // the \E and we don't see the end of the non-regular expression. if (result.charAt(result.length() - 1) == '\\') { result.append("E\\\\\\Q"); } return result.toString(); } public static String prepareNonRegularExpressionReplacement(String regexp) { StringBuffer result = new StringBuffer(regexp); int index = result.indexOf("\\"); while (index != -1) { result.replace(index, index + 1, "\\\\"); index = result.indexOf("\\", index + 2); } index = result.indexOf("$"); while (index != -1) { result.replace(index, index + 1, "\\$"); index = result.indexOf("$", index + 2); } // // Last character is a '\', make sure to escape otherwise it will escape // // the \E and we don't see the end of the non-regular expression. // if ( result.length() > 0 && result.charAt( result.length()-1) == '\\') { // result.append( "E\\\\\\Q"); // } return result.toString(); } }