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.

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.