Suppose I have the following regular expression in Python and I would like to use a variable instead of [1-12]. For example, my variable is currentMonth = 9
How can I plug currentMonth into the regular expression?
r"(?P<speaker>[A-Za-z\s.]+): (?P<month>[1-12])"
Use string formating to insert
currentMonthinto the regex pattern:By the way,
(?P<month>[1-12])probably does not do what you expect. The regex[1-12]matches1or2only. If you wanted to match one through twelve,you’d need
(?P<month>12|11|10|[1-9]).