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

I have already passed: Regular expression for repeating four repeating letters in a string using a Java pattern as well as Regular expression for repeating any character more than 10 times

But they are not useful in my case. They are great if I just want to check if a string contains duplicate characters (e.g. 1111, abccccd, 12aaaa3b, etc.). I want to check if a string contains only duplicate characters, only aab111, 1111222, 11222aaa, etc.

Can anyone help me with this?

+4
source share
1 answer

((.)\2+)+ :

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

:

  • (...): . ( 1)

    ((.)\2+)+
    ^^ 
    |+----- group 2
    +----- group 1
    
  • (.): ( ) 2 ( ).
  • \2: . (.) x, \2 x ( , x).
  • PATTERN+: PATTERN.
  • (.)\2+: .
+12

Source: https://habr.com/ru/post/1523279/


All Articles