Java Replace Strings: replaceFirst and replaceAll

Use replace, replaceFirst and replaceAll to swap strings, chars and CharSequences.

Replace. A dry wind causes a shift in the sand. The surface has changed. What exists is just temporary. Change and replacement is certain.

Strings too can be changed. There are many forms of the replace() method. Powerful Regex-based methods are available. With replaceFirst and replaceAll we specify what we want to replace.

An example. Here we use the version of replace() that replaces all instances of one char value with another. So we change all "a" letters to the underscore "_" character.
Tip: This replace call changes all characters with matching values, not just the first one. This is important to remember.
Java program that uses replace, char public class Program { public static void main(String[] args) { String value = "Java"; // Replace letter with underscore. String result = value.replace('a', '_'); System.out.println(result); } } Output J_v_

CharSequence, Strings. We also can call replace() with CharSequence arguments. A CharSequence is an interface that is implemented by the String class. So we can replace Strings.
Tip: This version of replace checks the entire string for all possible replacements. It does not just replace the first one.
Java program that uses replace, CharSequence public class Program { public static void main(String[] args) { String animals = "cat cat dog"; // Replace all CharSequences (strings) with another. String result = animals.replace("cat", "mouse"); System.out.println(result); } } Output mouse mouse dog

ReplaceFirst. This method only replaces the first occurrence of the string found. We also can use Regex with this method. Please see the replaceAll example for tips on Regex replacing.
Java program that uses replaceFirst public class Program { public static void main(String[] args) { String pets = "cat cat dog"; // Replace first instance of "cat". String result = pets.replaceFirst("cat", "bird"); System.out.println(result); } } Output bird cat dog

ReplaceAll, Regex. This program uses a regular expression to replace all matches of a pattern with a string. The "\d" codes mean "digit." We match 3 digits surrounded by "a" and "z."
So: The substrings a100z, a200z and a300z are matched and replaced. But the substring b100z is not.
Java program that uses replaceAll public class Program { public static void main(String[] args) { String codes = "a100z a200z a300z b100z"; // Replace all matches with a string. String result = codes.replaceAll("a\\d\\d\\dz", "a---z"); System.out.println(result); } } Output a---z a---z a---z b100z

Replace end. With the "$" metacharacter, we can match the end of a string. This allows us to use replaceFirst to replace an ending string.
Here: The string contains three "cats." We only replace the final, ending cat with a "dog" string.
Java program that replaces end string public class Program { public static void main(String[] args) { String pets = "cat cat cat"; // Use metacharacter to ensure the replacement is at the end. String result = pets.replaceFirst("cat$", "dog"); System.out.println(result); } } Output cat cat dog

Optimization. Sometimes we can use logic to avoid calling replace() when it is not needed. If many strings do not need to be processed, a method like contains() can reduce work.
Here: The first string contains HTML, so we call replace() on it. But the second string does not, so we skip it.
Tip: This optimization depends on the data being processed in a program, and the exact logic. But it is sometimes worth doing.
Java program that avoids replace calls public class Program { public static String replaceIfNeeded(String value) { // Test the string to see if any of the replacements can succeed. if (value.contains("<span>")) { value = value.replace("<span><b>", "*"); value = value.replace("<span><i>", "/"); } if (value.contains("</span>")) { value = value.replace("</b></span>", "*"); value = value.replace("</i></span>", "/"); } return value; } public static void main(String[] args) { // ... All replace calls are used on this string. String result = replaceIfNeeded("<span><b>Cat</b></span>"); System.out.println(result); // ... No replace calls are needed. result = replaceIfNeeded("Dog"); System.out.println(result); } } Output *Cat* Dog

Regex or string. Should we use a Regex or a String in replace? If only one constant pattern needs replacing, a String is simpler. But if differences may occur, a Regex is clearer.

StringBuilder. Replace on StringBuilder is different from the String method. With StringBuilder, we indicate a range with indexes, and then replace those characters with another string.StringBuilder

With replace, we gain powerful ways to change Strings. Each time, a new String is created. So all the data must be copied. With StringBuilder this inefficiency is reduced.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.