I'm trying to create a small, text restriction program in python. Basically, the user inputs the text, some filters (a for alphabetic, n for numeric, etc.). The user can combine filters (a and n for alpha-numeric, etc.) but I stumbled upon this:
if re.match("[a-zA-Z]", textToRestrict):
return True
else:
return False
Here's where things fall apart. Supposedly, with only alphabetic as a filter, the program will only accept strings, such as, say, dance
. However, the if statement still returns true
if the textToRestric
was, say, dance1234
(incorrect) while 1234dance
will return false
(correct).
Conversely, if I test for digits via [0-9]
, it would still return true
even if it contains alphabetic characters, provided that the characters aren't the first.
How do I use regex to match only a certain type, and in such a way that adding another type to it (like type string + type digit) allows for both types return true
?
UPDATE: This is the approach I used for multiple filters:
regex = ""
if FilterClass.ALPHABETIC in arguments:
regex += "[a-zA-Z]"
if FilterClass.CAPITAL_ALPHABETIC in arguments:
regex += "[A-Z]"
if FilterClass.NUMERIC in arguments:
regex += "\d"
if FilterClass.SPECIAL_CHARACTERS in arguments:
regex += "[^0-9a-zA-Z]*"
if FilterClass.DASH_UNDERSCORES in arguments:
regex += "[-_]*"
regall = "^(" + regex + ")+$"
if re.match(regall, textToRestrict):
return True
else:
return False
arguments
is a parameter inputted in by the user. The if statements check what's in there, and, supposedly, add more patterns to the regex string.