Java String Replace substituteIgnoreCase(String s, String pattern, String replacement)

Here you can find the source of substituteIgnoreCase(String s, String pattern, String replacement)

Description

Substitutes alls occurences of a pattern in a string, ignores character casing.

License

Apache License

Parameter

Parameter Description
s String to work on or null
pattern Pattern to search for
replacement String to replace for the pattern

Return

The result string or s itself if the pattern was not found

Declaration

public static String substituteIgnoreCase(String s, String pattern, String replacement) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w.  j  av a  2s .c  o m*/
 *   Copyright 2007 skynamics AG
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

import java.util.Iterator;

import java.util.Map;
import java.util.Set;

public class Main {
    /**
     * Substitutes alls occurences of a pattern in a string, ignores character casing.
     *
     * @param s String to work on or null
     * @param pattern Pattern to search for
     * @param replacement String to replace for the pattern
     * @return The result string or s itself if the pattern was not found
     */
    public static String substituteIgnoreCase(String s, String pattern, String replacement) {
        if (s == null || pattern == null)
            return s;
        int patLen = pattern.length();
        if (patLen == 0)
            return s;

        // We are allocating the string buffer only if we really need it,
        // i. e. if there is something to replace
        StringBuffer sb = null;

        int len = s.length();
        for (int i = 0; i < len; ++i) {
            if (s.regionMatches(true, i, pattern, 0, patLen)) {
                if (sb == null) {
                    // First replace action, copy the string so far
                    sb = new StringBuffer(len > 16 ? len : 16);
                    sb.append(s.substring(0, i));
                }
                sb.append(replacement);
                i += patLen - 1;
            } else {
                if (sb != null)
                    sb.append(s.charAt(i));
            }
        }
        return sb != null ? sb.toString() : s;
    }

    /**
     * Substitutes alls occurences of several patterns in a string.
     * Ignores character casing when comparing the string to the patterns.
     *
     * @param s String to work on
     * @param map Map containing the patterns as keys and the replacements as values
     * @return The result string or s itself if the string does not contain any of the patterns
     */
    public static String substituteIgnoreCase(String s, Map map) {
        return substitute(s, map, true);
    }

    /**
     * Appends 2 strings to a string buffer.
     * @nowarn
     */
    public static void append(StringBuffer sb, String s1, String s2) {
        sb.append(s1);
        sb.append(s2);
    }

    /**
     * Appends 3 strings to a string buffer.
     * @nowarn
     */
    public static void append(StringBuffer sb, String s1, String s2, String s3) {
        sb.append(s1);
        sb.append(s2);
        sb.append(s3);
    }

    /**
     * Appends 4 strings to a string buffer.
     * @nowarn
     */
    public static void append(StringBuffer sb, String s1, String s2, String s3, String s4) {
        sb.append(s1);
        sb.append(s2);
        sb.append(s3);
        sb.append(s4);
    }

    /**
     * Appends 5 strings to a string buffer.
     * @nowarn
     */
    public static void append(StringBuffer sb, String s1, String s2, String s3, String s4, String s5) {
        sb.append(s1);
        sb.append(s2);
        sb.append(s3);
        sb.append(s4);
        sb.append(s5);
    }

    /**
     * Substitutes alls occurences of a pattern in a string.
     *
     * @param s String to work on or null
     * @param pattern Pattern to search for
     * @param replacement String to replace for the pattern or null for nothing
     * @return The result string or s itself if the pattern was not found
     */
    public static String substitute(String s, String pattern, String replacement) {
        if (s == null || pattern == null)
            return s;
        if (s.indexOf(pattern) < 0) {
            // Prevents unnecessary allocation and parsing
            // in case the string does not contain the pattern
            return s;
        }

        int patLen = pattern.length();
        if (patLen == 0)
            return s;

        int len = s.length();
        StringBuffer sb = new StringBuffer(len > 16 ? len : 16);

        for (int i = 0; i < len; ++i) {
            if (s.startsWith(pattern, i)) {
                if (replacement != null) {
                    sb.append(replacement);
                }
                i += patLen - 1;
            } else {
                sb.append(s.charAt(i));
            }
        }
        return sb.toString();
    }

    /**
     * Substitutes alls occurences of several patterns in a string.
     * The pattern comparisons case-dependent.
     *
     * @param s String to work on
     * @param map Map containing the patterns as keys and the replacements as values
     * @return The result string or s itself if the string does not contain any of the patterns
     */
    public static String substitute(String s, Map map) {
        return substitute(s, map, false);
    }

    /**
     * Substitutes alls occurences of several patterns in a string.
     *
     * @param s String to work on
     * @param map Map containing the patterns as keys and the replacements as values
     * @param ignoreCase
     *      true   Ignores character casing when comparing the string to the patterns<br>
     *      false   Comparisons are case-dependent
     * @return The result string or s itself if the string does not contain any of the patterns
     */
    private static String substitute(String s, Map map, boolean ignoreCase) {
        if (s == null || map == null)
            return s;

        // We need to iterate the
        Set patternSet = map.keySet();
        if (patternSet.size() == 0)
            return s;

        // We are allocating the string buffer only if we really need it,
        // i. e. if there is something to replace
        StringBuffer sb = null;

        int len = s.length();
        for (int i = 0; i < len; ++i) {
            String matchingPattern = null;

            for (Iterator it = patternSet.iterator(); it.hasNext();) {
                String pattern = (String) it.next();

                boolean match = ignoreCase ? s.regionMatches(true, i, pattern, 0, pattern.length())
                        : s.startsWith(pattern, i);

                if (match) {
                    matchingPattern = pattern;
                    break;
                }
            }
            if (matchingPattern != null) {
                if (sb == null) {
                    // First replace action, copy the string so far
                    sb = new StringBuffer(len > 16 ? len : 16);
                    sb.append(s.substring(0, i));
                }
                sb.append((String) map.get(matchingPattern));
                i += matchingPattern.length() - 1;
            } else {
                if (sb != null)
                    sb.append(s.charAt(i));
            }
        }

        return sb != null ? sb.toString() : s;
    }
}

Related

  1. replaceUnsafeNamespaceDelimiters(String input)
  2. replaceWildcards(String wildcardPattern)
  3. searchAndReplace(String source, String search, String replace)
  4. strReplaceOld(String strText, String strFrom, String strTo, boolean bMultiple)
  5. subStitute(String value, String pattern, String replacement)