Java Regex String Replace replace(CharSequence target, CharSequence replacement, String string)

Here you can find the source of replace(CharSequence target, CharSequence replacement, String string)

Description

replace

License

Open Source License

Declaration

public static String replace(CharSequence target, CharSequence replacement, String string) 

Method Source Code


//package com.java2s;
import java.util.regex.Pattern;

public class Main {
    public static String replace(CharSequence target, CharSequence replacement, String string) {
        return Pattern.compile(quote(target.toString()) /* Pattern.LITERAL jdk 1.4 */).matcher(string)
                .replaceAll(/* Matcher. jdk 1.4 */ quoteReplacement(replacement.toString()));
    }//from www .j  a  va  2 s  .  c om

    private static String quote(String s) {
        int slashEIndex = s.indexOf("\\E");
        if (slashEIndex == -1)
            return "\\Q" + s + "\\E";

        StringBuffer sb = new StringBuffer(s.length() * 2);
        sb.append("\\Q");
        slashEIndex = 0;
        int current = 0;
        while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
            sb.append(s.substring(current, slashEIndex));
            current = slashEIndex + 2;
            sb.append("\\E\\\\E\\Q");
        }
        sb.append(s.substring(current, s.length()));
        sb.append("\\E");
        return sb.toString();
    }

    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();
    }
}

Related

  1. replace$(String text, Map vars)
  2. replace(final String regex, final String replacement, final StringBuffer source, boolean all)
  3. replace(final String template, final Map map, final String prefix, final String suffix, boolean useMapForMatching)
  4. replace(Matcher m, String rv, Object value)
  5. replace(Pattern pattern, String src, Function handler)