Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - String replaceAll() method



replaceAll() method replaces all occurrences of a captured group by the result of a closure on that text.

Syntax

void replaceAll(String regex, String replacement)

Parameters

  • regex − the regular expression to which this string is to be matched.

  • replacement − the string which would replace found expression.

Return Value

The new value of the string.

Example - Replacing a Meta Character from a String

Following is an example of the usage of replaceAll() method.

Example.groovy

class Example { 
   static void main(String[] args) { 
      String str1 = "!!Tutorials!!Point", str2;
      String substr = "**", regex = "!!";    
      
      // prints string1
      println("String = " + str1);    
      
      /* replaces each substring of this string that matches the given
      regular expression with the given replacement */
      str2 = str1.replaceAll(regex, substr);    
      println("After Replacing = " + str2);     
   } 
}

Output

When we run the above program, we will get the following result −

String = !!Tutorials!!Point
After Replacing = **Tutorials**Point

Example - Replacing Occurrences of a Word from a String

Following is an example of the usage of replaceAll() method.

Example.groovy

class Example { 
   static void main(String[] args) { 
      String str = "Next time there won't be a next time after a certain time.";
      println("The given string is: " + str);
      
      // replacing all occurrences of "time" to "day"
      String newString = str.replaceAll("time", "day");
      println("The new replaced string is: " + newString);       
   } 
}

Output

When we run the above program, we will get the following result −

The given string is: Next time there won't be a next time after a certain time.
The new replaced string is: Next day there won't be a next day after a certain day.

Example - Replacing All Whitespace Character from a String

Following is an example of the usage of replaceAll() method.

Example.groovy

class Example { 
   static void main(String[] args) { 	      
      String str = "Next time there won't be a next time after a certain time.";
      System.out.println("The given string is: " + str);
      
      // replacing all occurrences of "time" to "day"
      String newString = str.replaceAll("\\s", "");
      System.out.println("The new replaced string is: " + newString);
   } 
}

Output

When we run the above program, we will get the following result −

The given string is: Next time there won't be a next time after a certain time.
The new replaced string is: Nexttimetherewon'tbeanexttimeafteracertaintime.
groovy_strings.htm
Advertisements