What is the regex pattern to determine if a string solely consists of a single repeating character?
e.g.
"aaaaaaa" = true
"aaabbbb" = false
"$$$$$$$" = true
This question checks if a string only contains repeating characters (e.g. "aabb") however I need to determine if it is a single repeating character.
You can try with back reference
^(.)\1{1,}$
DEMO
Pattern Explanation:
^ the beginning of the string
( group and capture to \1:
. any character except \n
) end of \1
\1{1,} what was matched by capture \1 (at least 1 times)
$ the end of the string
Backreferences match the same text as previously matched by a capturing group. The backreference \1
(backslash one) references the first capturing group. \1
matches the exact same text that was matched by the first capturing group.
In Java you can try
"aaaaaaaa".matches("(.)\\1+") // true
There is no need for ^
and $
because String.matches()
looks for whole string match.
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