Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a regular expression to find if string contains only repeating characters?

Tags:

java

string

regex

I've already gone through: Regex to match four repeated letters in a string using a Java pattern and Regular expression to match any character being repeated more than 10 times

But they aren't useful in my case. They are fine if I just want to check if a string is containing repeated characters (like 1111, abccccd, 12aaaa3b, etc.). What I want is to check if string is comprising entirely of repeated characters only i.e. aabb111, 1111222, 11222aaa, etc.

Can anyone help me out with this?

like image 959
Kiran Parmar Avatar asked Dec 16 '22 02:12

Kiran Parmar


1 Answers

Use ((.)\2+)+ as pattern:

String pattern = "((.)\\2+)+";
System.out.println("a".matches(pattern));        // false
System.out.println("1aaa".matches(pattern));     // false
System.out.println("aa".matches(pattern));       // true
System.out.println("aabb111".matches(pattern));  // true
System.out.println("1111222".matches(pattern));  // true
System.out.println("11222aaa".matches(pattern)); // true
System.out.println("etc.".matches(pattern));     // false

About the pattern:

  • (...): capture matched part as group. (starting from 1)

    ((.)\2+)+
    ^^ 
    |+----- group 2
    +----- group 1
    
  • (.): match any character (except newline) and capture it as group 2 (because it come after enclosing parenthesis).
  • \2: backreference to the matched group. If (.) matched a character x, \2 matches another x (not any character, but only x).
  • PATTERN+: matches one or more matches of PATTERN.
  • (.)\2+: match repeating characters greedy.
like image 60
falsetru Avatar answered May 08 '23 07:05

falsetru