Python: Validate String: Lowercase, Digit, Underscore: re.match, bool()

Using re.match to Validate a String

nick3499
1 min readJun 23, 2018

from re import match as m

  • import the match() method of the re module (regular expressions)

def validate_str(s):

  • defines function named validate_str with the formal parameter named s 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 characteristics
  • m() is the match method
  • bool() returns the Boolean constant True or False. 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 string
  • s is placeholder for the string being matched

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet