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?
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With