Search code examples
javaregexstringrepeat

Regex to determine if string is a single repeating character


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.


Solution

  • You can try a backreference

    ^(.)\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.