Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to determine if string is a single repeating character [duplicate]

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.

like image 660
Continuity8 Avatar asked Mar 20 '15 03:03

Continuity8


1 Answers

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.

like image 73
Braj Avatar answered Nov 04 '22 13:11

Braj