1

I need to determine if a string is composed of a certain repeating character, for example eeeee, 55555, or !!!.

I know this regex 'e{1,15}' can match eeeee but it obviously can't match 555. I tried [a-z0-9]{1-15} but it matches even the strings I don't need like Hello.

The solution doesn't have to be regex. I just can't think of any other way to do this.

CH123
  • 251
  • 1
  • 5
  • 15
  • 2
    Possible duplicate of [Regular expression to match any character being repeated more than 10 times](https://stackoverflow.com/questions/1660694/regular-expression-to-match-any-character-being-repeated-more-than-10-times). You can easily adapt the regex from the accepted anser to suit your needs. – Malte Hartwig Sep 12 '17 at 09:17

3 Answers3

4

A string consists of a single repeating character if and only if all characters in it are the same. You can easily test that by constructing a set out of the string: set('55555').

All characters are the same if and only if the set has size 1:

>>> len(set('55555')) == 1
True
>>> len(set('Hello')) == 1
False
>>> len(set('')) == 1
False

If you want to allow the empty string as well (set size 0), then use <= 1 instead of == 1.

Thomas
  • 174,939
  • 50
  • 355
  • 478
1

Regex solution (via re.search() function):

import re

s = 'eeeee'
print(bool(re.search(r'^(.)\1+$', s)))   # True

s = 'ee44e'
print(bool(re.search(r'^(.)\1+$', s)))   # False

^(.)\1+$ :

  • (.) - capture any character

  • \1+ - backreference to the previously captured group, repeated one or many times

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

You do not have to use regex for this, a test to determine if all characters in the string are the same will produce the desired output:

s = "eee"
assert len(s) > 0
reference = s[0]
result = all([c==reference for c in s])

Or use set as Thomas showed, which is probably a better way.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80