Java Utililty Methods Regex String Replace

List of utility methods to do Regex String Replace

Description

The list of methods to do Regex String Replace are organized into topic(s).

Method

Stringreplace(String text, String find, String match, boolean useRegex, boolean isCaseSensitive)
replace
if (useRegex) {
    if (isCaseSensitive) {
        return text.replaceAll(find, match);
    } else {
        return text.replaceAll("(?i)" + find, match);
} else {
    if (isCaseSensitive) {
...
Stringreplace(String text, String findPattern, String replacePattern)
Replace any text within a text using regular expressions
Pattern pattern = Pattern.compile(findPattern);
Matcher matcher = pattern.matcher(text);
return matcher.replaceAll(replacePattern);
Stringreplace(String text, String targetText, String newText)
Replace all occurances of the target text with the provided replacement text.
Pattern pattern = Pattern.compile(targetText, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
return matcher.replaceAll(newText);
Stringreplace(String text, String[] searchStrings, String[] replacements)
Replace multiple search strings simultaneously
validateParams(text, searchStrings, replacements);
if (searchStrings.length == 0) {
    return text;
Map<String, String> searchStringsToReplacements = zipToMap(searchStrings, replacements);
StringBuffer buffer = new StringBuffer();
Matcher matcher = buildPattern(searchStrings).matcher(text);
while (matcher.find()) {
...
Stringreplace(String val)
Replaces any ${} strings with their corresponding environent variable.
Matcher matcher = p.matcher(val);
StringBuffer buf = new StringBuffer();
while (matcher.find()) {
    String envVar = matcher.group(1);
    String envVal = System.getProperty(envVar);
    if (envVal == null)
        envVal = "NOT-SPECIFIED";
    matcher.appendReplacement(buf, envVal.replace("\\", "\\\\"));
...
Stringreplace(String value)
replace
if (value == null)
    return null;
StringBuffer sb = new StringBuffer(256);
Matcher m = VAR_PTN.matcher(value);
while (m.find()) {
    String propValue = System.getProperty(m.group(1));
    if (propValue == null)
        propValue = "";
...
Stringreplace_values(HashMap values, String str)
replacvalues
StringBuilder sbStr = new StringBuilder();
int i = 0;
for (String s : values.keySet()) {
    i++;
    sbStr.append(s);
    if (i < values.size()) {
        sbStr.append("|");
String patternString = "%(" + sbStr.toString() + ")%";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(sb, values.get(matcher.group(1)));
matcher.appendTail(sb);
return sb.toString();
Stringreplace_with_in(String aStringToReplace, String aNewString, String aString)
replacwitin
Pattern pattern = Pattern.compile(aStringToReplace);
Matcher matcher = pattern.matcher(aString);
return matcher.replaceAll(aNewString);