Beth Wegner
Beth Wegner

Reputation: 13

Find 3 or more repeating charaters in a string

I'm trying to find any occurrences of a character repeating more than 2 times in a user entered string. I have this, but it doesn't go into the if statement.

password = asDFwe23df333

s = re.compile('((\w)\2{2,})')

m = s.search(password)

if m:
     print ("Password cannot contain 3 or more of the same characters in a row\n")

     sys.exit(0)

Upvotes: 1

Views: 128

Answers (2)

Gorbag
Gorbag

Reputation: 263

Can't you simply go through the whole string and everytime you found a character equal to the previous, you incremented a counter, till it reached the value of 3? If the character was different from the previous, it would only be a matter of setting the counter back to 0.

EDIT: Or, you can use:

s = 'aaabbb' re.findall(r'((\w)\2{2,})', s)

And check if the list returned by the second line has any elements.

Upvotes: -1

lmortenson
lmortenson

Reputation: 1605

You need to prefix your regex with the letter 'r', like so:

s = re.compile(r'((\w)\2{2,})')

If you don't do that, then you'll have to double up on all your backslashes since Python normally treats backlashes like an escape character in its normal strings. Since that makes regexes even harder to read then they normally are, most regexes in Python include that prefix.

Also, in your included code your password isn't in quotes, but I'm assuming it has quotes in your code.

Upvotes: 3

Related Questions