Python: Validate String: Lowercase, Digit, Underscore: re.match, bool()
from re import match as m
import
thematch()
method of there
module (regular expressions)
def validate_str(s):
- defines function named
validate_str
with the formal parameter nameds
which becomes a placeholder for the string being validated
return bool(m("[0–9a-z_]{4,16}$", s))
[0–9a-z_]{4,16}$
is the regex pattern (regular expression) used to match specific string characteristicsm()
is the match methodbool()
returns the Boolean constantTrue
orFalse
.True
, if the entire string matches the regex pattern.
Regex Pattern
[0–9]
matches digits[a-z]
matches lowercase letters_
matches underscores{4,16}
limits string length match from ≥4
to ≤16
$
operator indicates the end of the strings
is placeholder for the string being matched