9

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.

Community
  • 1
  • 1
Continuity8
  • 2,403
  • 4
  • 19
  • 34
  • `^(.)\1+$` maybe? Depends on the language. [Regex101](https://regex101.com/r/lS5aG7/1) – Matt Mar 20 '15 at 03:40
  • Oops Java, just added tag. – Continuity8 Mar 20 '15 at 03:50
  • if someone wants opposite of this one, allow only if string doesn't contain same character start to end, this is the regex ^(?!(.)\1+$).* https://stackoverflow.com/questions/8610743/how-to-negate-any-regular-expression-in-java this link helped me to negate it – Satish Patro Dec 08 '20 at 10:36
  • @PSatishPatro you could always just use the regix in the answer to this question with the java 'not' operator: !string.matches(^(.)\1{1,}$); – Continuity8 Dec 09 '20 at 18:21

2 Answers2

14

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.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Braj
  • 46,415
  • 5
  • 60
  • 76
10

this really depends on your language but in general this would match a line with all the same character.

^(.)\1+$

Regex101 Example

  • ^ assert position at start of a line
  • 1st Capturing group (.)
  • \1+ matches the same text as most recently matched by the 1st capturing group Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
  • $ assert position at end of a line
Matt
  • 45,022
  • 8
  • 78
  • 119