Replace all words with another string with Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

To replace all words with another String using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.

Declaration − The java.lang.String.replaceAll() method is declared as follows −

public String replaceAll(String regex, String replaced)  

Let us see a program to replace all words with another string with Java Regular Expressions −

Example

 Live Demo

public class Example {
   public static void main( String args[] ) {
      String str = new String("Good Harry Good");
      System.out.println( "Initial String : "+ str);
      // replacing all words with with "Bad"
      str = str.replaceAll( "\\w+" , "Bad" );
      System.out.println( "The String after substitution : "+str );
   }
}

Output

Initial String : Good Harry Good
The String after substitution : Bad Bad Bad
raja
Published on 08-Jan-2019 16:02:03
Advertisements