All for Joomla All for Webmasters

Java String replaceAll

The java string replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.


  1. public String replaceAll(String regex, String replacement)


regex : regular expression

replacement : replacement sequence of characters


replaced string

Java String replaceAll() example: replace character

Let’s see an example to replace all the occurrences of a single character.

  1. public class ReplaceAllExample1{
  2. public static void main(String args[]){
  3. String s1=“makeforsure is a very good website”;
  4. String replaceString=s1.replaceAll(“a”,“e”);//replaces all occurrences of “a” to “e”
  5. System.out.println(replaceString);
  6. }}
makeforsure is e very good website

Java String replaceAll() example: replace word

Let’s see an example to replace all the occurrences of single word or set of words.

  1. public class ReplaceAllExample2{
  2. public static void main(String args[]){
  3. String s1=“My name is Khan. My name is Bob. My name is rahul.”;
  4. String replaceString=s1.replaceAll(“is”,“was”);//replaces all occurrences of “is” to “was”
  5. System.out.println(replaceString);
  6. }}
My name was Khan. My name was Bob. My name was rahul.

Java String replaceAll() example: remove white spaces

Let’s see an example to remove all the occurrences of white spaces.

  1. public class ReplaceAllExample3{
  2. public static void main(String args[]){
  3. String s1=“My name is Khan. My name is Bob. My name is Sonoo.”;
  4. String replaceString=s1.replaceAll(“\\s”,“”);
  5. System.out.println(replaceString);
  6. }}
submit to reddit

Leave a Reply