Here you can find the source of replaceAllStrictly(String src, String search, String replacement, boolean entirelyMatch, boolean caseSensitive)
public static String replaceAllStrictly(String src, String search, String replacement, boolean entirelyMatch, boolean caseSensitive)
//package com.java2s; // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /**/*ww w . j a v a2 s. c o m*/ * ignore regex * */ public static String replaceAllStrictly(String src, String search, String replacement, boolean entirelyMatch, boolean caseSensitive) { // case 1: if (search == null) { if (src == null) { return replacement; // regex == null && src == null } else { return src; // regex == null && src != null } } else { // case 2: if (src == null) { return null; // regex != null && src == null } else { // case 3: if (replacement == null || entirelyMatch) { if ((caseSensitive && src.equals(search)) || (!caseSensitive && src.equalsIgnoreCase(search))) { // regex != null && src != null && replacement != null, and match the whole src return replacement; } else { return src; // can't match the whole src } } else { int flag = caseSensitive ? Pattern.LITERAL : Pattern.LITERAL | Pattern.CASE_INSENSITIVE; return Pattern.compile(search, flag).matcher(src) .replaceAll(Matcher.quoteReplacement(replacement)); } } } } /** * to discuss the case: src == null || regex == null || replacement == null * */ public static String replaceAll(String src, String regex, String replacement) { // case 1: if (regex == null) { if (src == null) { return replacement; // regex == null && src == null } else { return src; // regex == null && src != null } } else { // case 2: if (src == null) { return null; // regex != null && src == null } else { // case 3: if (replacement == null) { if (src.matches(regex)) { // regex != null && src != null && replacement != null, and match the whole src return replacement; } else { return src; // can't match the whole src } } else { // regex != null && src != null && replacement != null return src.replaceAll(regex, replacement); } } } } }