How to Remove Duplicates from a String in Java Using Regex ?
Last Updated :
12 Feb, 2024
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
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GFGRemoveDuplicates {
public static void main(String[] args) {
String str = "Java programming" ;
String result = removeDuplicates(str);
System.out.println( "Original String: " + str);
System.out.println( "String after removing duplicates: " + result);
}
private static String removeDuplicates(String input) {
String regex = "(.)(?=.*\\1)" ;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
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.
Share your thoughts in the comments
Please Login to comment...