[Tutor] Need help on regular expresions

Mats Wichmann mats at wichmann.us
Sun Nov 7 09:54:48 EST 2021


On 11/6/21 10:09, Dennis Lee Bieber wrote:
> On Sat, 6 Nov 2021 20:23:45 +0530, Manprit Singh
> <manpritsinghece at gmail.com> declaimed the following:
> 
>>
>> How would I do it with regular expressions ? Since this problem will be
>> very ugly with regular string methods,  that's why I would like to try it
>> with re's.
>>
> 	I wouldn't...
> 
> 	To my understanding, regex do not do COUNTING, so your first criteria
> is not possible. You CAN specify that a regex matches, say, four
> CONSECUTIVE digits (using \d{4] ), but you can't say "match four SCATTERED
> digits".
> 
> https://docs.microsoft.com/en-us/dotnet/standard/base-types/quantifiers-in-regular-expressions
> 
> 	It also doesn't seem that difficult using string methods...
> 
> -=-=-=-
> 
> TESTTEXT = "aG4cD1_23fg"
> TESTTEXT2 = "Ag4C1_23Fg"
> TESTTEXT3 = "Ag4Cd123Fg"

Just for grins, here's a slightly different take on the same, hopefully 
reinforcing that what first seemed ugly maybe isn't so ugly (by all 
means, do learn regular expressions, though, there are places they are 
valuable, although we keep rehasing the old saw here: "I have a problem. 
I know, I'll use regular expressions". "Now you have two problems!"):

import sys
from collections import Counter
from string import ascii_letters, digits
under = '_'

s = "aG4cD1_23f"
if len(s) != 10:
     print(f"String is not 10 chars long ({len(s)})")
     sys.exit(1)

# set targets
cnt = Counter(letter=5, digit=4, underscore=1)

for l in s:
     if l in ascii_letters:
         cnt['letter'] -= 1
     elif l in digits:
         cnt['digit'] -= 1
     elif l in under:
         cnt['underscore'] -= 1

if any([cnt['underscore'], cnt['digit'], cnt['letter']]):
     print("Invalid string")



More information about the Tutor mailing list