Replacing all the matched contents Java regular expressions


Once you compile the required regular expression and retrieved the matcher object by passing the input string as a parameter to the matcher() method.

You can replace all the matched parts of the input string with another str4ing using the replaceAll() method of the Matcher class.

This method accepts a string (replacement string) and replaces all the matches in the input string with it and returns the result.

Example 1

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\\t+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("No.of matches: "+count);
      String result = matcher.replaceAll(" ");
      System.out.println("Result: "+result);
   }
}

Output

Enter input text:
sample text with tab spaces
No.of matches: 4
Result: sample text with tab spaces

In the same way you can replace the first match using the replaceFirst() method of the Matcher class.

Example 2

 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "\\d";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("No.of matches: "+count);
      String result = matcher.replaceFirst("#");
      System.out.println("Result: "+result);
   }
}

Output

Enter input text:
test data 1 2 3
No.of matches: 3
Result: test data # 2 3
raja
Published on 13-Jan-2020 06:33:20
Advertisements