Open In App

How to Remove Duplicates from a String in Java Using Regex ?

Last Updated : 12 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java programming, Regex (regular expressions) is a very important mechanism. It can be used to match patterns in strings. Regular expressions provide a short and simple syntax for describing the patterns of the text.

In this article, we will be learning how to remove duplicates from a String in Java using Regex.

Regex Implementation:

  • Pattern: It is a pre-defined class. It can be used to represent the compiled version of a regular expression.
  • Matchers: It is a class, that is used to match the pattern against a given input string and provides methods for matching, finding, replacing, and other operations.

Program to Remove Duplicates From a String in Java in Regex

Below is the Program to Remove Duplicates From a String in Java in Regex:

Java
// Java Program to remove duplicates from a String in Java in regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GFGRemoveDuplicates {
    //main method
    public static void main(String[] args) {
        String str = "Java programming";

        // Use regex to remove duplicate characters
        String result = removeDuplicates(str);

      //print the original string
        System.out.println("Original String: " + str);
      //print the string after removing the duplicates
        System.out.println("String after removing duplicates: " + result);
    }

    private static String removeDuplicates(String input) {
        // Define a regex pattern to match any duplicated character
        String regex = "(.)(?=.*\\1)";

        // Create a Pattern object
        Pattern pattern = Pattern.compile(regex);

        // Create a Matcher
        Matcher matcher = pattern.matcher(input);

        // Use replaceAll to remove duplicates
        return matcher.replaceAll("");
    }
}

Output
Original String: Java programming
String after removing duplicates: Jv poraming

Explanation of the above Program:

  • In the above java program, it demonstrates that how to remove the duplicate characters of the given string.
  • It can be implements using Patter and Matchers.
  • First define the regex expression to remove the duplicates((.)(?=.*\\1))
  • Then create the pattern object to compile the regex after that create the matcher that can be used to remove the duplicates characters into the program.

Next Article

Similar Reads