Java String ReplaceAll: How to Replace Certain Elements of a String

java iteratorJava was initially developed by Sun Microsystems.  It is an object-oriented and platform-independent programming language. Its underlying philosophy is – Write Once, Run Anywhere. When a Java program is compiled, the result is platform independent byte code. The latter is interpreted by Java Virtual Machine(JVM)  into the machine code of the platform it is using. Java is known to be secure and robust. It supports multithreading and is ideal for distributed environments. Java is used to create both web applications and stand-alone applications. One of the significant features of Java is automatic memory management. It’s a strongly typed language and is also case sensitive. Programmers with a C++ background will find it easy to migrate to the Java programming language.

In this beginner’s level tutorial, we walk you through the Java String function replaceAll(). If you’re new to Java, you may want to first take this beginners course on Java to get started.

What are Strings?

Strings are the type used to store any text and are often used in Java programs. They are defined as a sequence of characters. Java’s String class provides methods to create and manipulate strings. There exist methods to concatenate strings, calculate the length of a particular string, format strings, search for substrings and more. The java.lang package encapsulates the String class. The toString() method is found in all Java objects. This method returns a String object. Also, String values are always enclosed in double quotes.

Another way to represent strings in Java is to use an array of characters. However, the latter is different from a String object. To learn more about strings and character arrays in Java, you can take this course.

Introduction to the ReplaceAll() Method

The replaceAll() method is used to replace all the occurrences of  a regular expression or substring, within a larger string,  with a new string. The syntax of the replaceAll() method is as follows:-

public String replaceAll(String regex, String replacement)

The two parameters are –

  1. regex – the regular expression to match
  2. replacement – the string to be substituted for every match

Here, first the substring(s) of the string that matches the regular expression parameter is determined. Then they are replaced or substituted with the 2nd parameter passed i.e replacement.

This method is public and returns a String value. The exception ‘PatternSyntaxException’ is thrown in case of error in the regular expression’s syntax.

String objects in general cannot be modified. Whenever, you try to change its value, the value of the existing String object is not changed, instead a new string object is created to hold the new value. Hence whenever, replaceAll() function is called, it creates a new string object.

Introduction to Regular Expressions

A regular expression is defined as a pattern that describes some text. It can be abbreviated into “regex”. Regular expressions offer convenience to search, modify or manipulate text. It’s pattern may not match, match only once or match multiple times for a particular string. In Java, Strings provide support for regular expressions. Some of the methods are split(), replace() and matches().

For in-depth information about regular expressions, you can take this course which shows how regular expressions can be used in Java.

Example 1: Program to replace single characters

import  java.lang.String;

public class Example1 {

public static void main(String[] args) {

String str = "Strings are an important part of the Java programming language";

String Str1 = str.replaceAll("a", "b");

System.out.println(Str1);

Str1 = Str1.replaceAll("e", "1");

System.out.println(Str1);

Str1 = Str1.replaceAll("t", "T");

System.out.println(Str1);

Str1 = Str1.replaceAll("p", "");

System.out.println(Str1);

Str1 = Str1.replaceAll("J", "That");

System.out.println(Str1);

}

}

In the above program, the package java.lang.String is imported – so we can use the String class in this program. Then, the class keyword is used to create a new class object called Example1. The public keyword is an access specifier that makes Example1 accessible to all. The main() method begins the execution of the Java program. The return type of this method is void, which means that the main()  method does not return any value. The static key word ensures that there is only one instance of main () making the method class specific, and not object specific. We declare the str of type String data type. Then we assign it a string value. Here we have used the replaceAll() function to replace characters with other characters, numbers or  space characters. Also we have tried to replace lowercase characters with uppercase characters. The replaceAll() method is case sensitive. So it treats uppercase characters differently from their lowercase equivalents. In case there are no occurrences of a targeted character, this method will return an unchanged string value which was passed to it. All statements of the above program are terminated by a semi-colon. Learn how to write your own programs in Java with this course.

Example 2: Program to Replace Character Sequences

import  java.lang.String;

public class Example2 {

public static void main(String[] args) {

String str = "Hello World! Welcome to this Java Programming Tutorial";

String Str1 = str.replaceAll("Hello", "Good Morning");

System.out.println(Str1);

Str1 = str.replaceAll("this", "that");

System.out.println(Str1);

Str1 = str.replaceAll("to", "");

System.out.println(Str1);

Str1 = str.replaceAll("Welcome", "");

System.out.println(Str1);

}

}

Here the replaceAll() is used to replace character sequences with another character sequence or with an individual character.

Example 3: Program using Regular Expression

import  java.lang.String;

public class StringReplaceAllExample {

public static void main(String[] args) {

String str = "Introduction 1231 to  124 basic 1243 programming 34563 concepts 5455";

String Str1 = str.replaceAll("[0-9]+", "");

System.out.println(Str1);

Str1 = str.replaceAll("[a-zA-Z]+", "Java");

System.out.println(Str1);

}

}

The output of this program is as follows.

Introduction  to   basic  programming  concepts
Java 1231 Java 124 Java 1243 Java 34563 Java 5455

Other Methods to Replace Strings

String Class in Java provides three other methods to replace String.

They are :-

  • replace(char oldChar, char newChar)
  • replace(CharSequence target, CharSequence replacement)
  • replaceFirst(String regex, String replacement)

Hope this tutorial gave you a good idea of how to replace strings in Java. Do try out the examples on your own and play around with the code. Once you’re ready to move to the next level, you can take this advanced course on Java programming to give you more insights into advanced Java techniques.