Thursday 23 May 2019

Java: Regex to check immediate repeated characters in a string


Example 1: If the string is "abcdbaa", repeated characters are "a". Even though b is repeated twice, since it is repeated in different places (not adjacent), it is not considered as immediate repeated character.

Example 2: If the string is "abcdbaabb", repeated characters are "a, b".

"(\\w)\\1+" pattern used to get the repeated characters.

App.java
package com.sample.app;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class App {

 private static List<String> repeatedChars(String str) {

  Pattern pattern = Pattern.compile("(\\w)\\1+");
  Matcher matcher = pattern.matcher(str);

  List<String> list = new ArrayList<>();
  while (matcher.find()) {
   list.add(matcher.group(1));
  }
  
  return list;
 }

 public static void main(String args[]) throws FileNotFoundException {
  System.out.println("Repeated characters in \"abcdbaa\" : " + repeatedChars("abcdbaa"));
  System.out.println("Repeated characters in \"abcdbaabb\" : " + repeatedChars("abcdbaabb"));
 }
}

Output
Repeated characters in "abcdbaa" : [a]
Repeated characters in "abcdbaabb" : [a, b]

If you are new to regular expressions, I would recommend you to go through my below tutorial series.



You may like

No comments:

Post a Comment