[Tutor] Need help on regular expresions

Dennis Lee Bieber wlfraed at ix.netcom.com
Sat Nov 6 12:09:54 EDT 2021


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"

def checkText(text, lenLimit, reqDigits, reqUnderscore, reqAlpha):
    if lenLimit != sum([reqDigits, reqUnderscore, reqAlpha]):
        raise ValueError("Sum of required characters does not match length
limit")
    for ch in text:
        if ch == "_": reqUnderscore -= 1
        if ch.isdecimal(): reqDigits -= 1   #or maybe .isdigit()
        if ch.isalpha(): reqAlpha -= 1      #or maybe .isascii()

    return (len(text) == lenLimit
            and reqDigits == 0
            and reqAlpha == 0
            and reqUnderscore == 0)

if __name__ == "__main__":
    print("%s\t%s" % (TESTTEXT, checkText(TESTTEXT, 10, 4, 1, 5)))
    print("%s\t%s" % (TESTTEXT2, checkText(TESTTEXT2, 10, 4, 1, 5)))
    print("%s\t%s" % (TESTTEXT3, checkText(TESTTEXT3, 10, 4, 1, 5)))
    print("%s\t%s" % (TESTTEXT3, checkText(TESTTEXT3, 10, 4, 2, 5)))

-=-=-=-
aG4cD1_23fg	False
Ag4C1_23Fg	True
Ag4Cd123Fg	False
Traceback (most recent call last):
  File
"C:\Python38\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 326, in RunScript
    exec(codeObject, __main__.__dict__)
  File "C:\Users\Wulfraed\Documents\_Hg-Repositories\Python
Progs\CheckText.py", line 23, in <module>
    print("%s\t%s" % (TESTTEXT3, checkText(TESTTEXT3, 10, 4, 2, 5)))
  File "C:\Users\Wulfraed\Documents\_Hg-Repositories\Python
Progs\CheckText.py", line 8, in checkText
    raise ValueError("Sum of required characters does not match length
limit")
ValueError: Sum of required characters does not match length limit 
-=-=-=-


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list