TheDeveloperBlog.com


Java

Java Replace Strings: replaceFirst and replaceAll

Replace. A substring can be replaced within a String in many ways. And many forms of the replace() method are available. The simplest use chars or CharSequences.


Regex. Powerful Regex-based methods are also available. We can match strings with Regex and replace the first (with replaceFirst) or every match (with replaceAll).


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.

Based on:

Java 7

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

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.