在正则表达式(python)中使用其值为整数的变量

4 python regex

假设我在Python中具有以下正则表达式,并且我想使用变量而不是[1-12]。例如,我的变量是currentMonth = 9

如何将currentMonth插入正则表达式?

r"(?P<speaker>[A-Za-z\s.]+): (?P<month>[1-12])"
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 5

使用字符串格式插入currentMonth到正则表达式模式中:

r"(?P<speaker>[A-Za-z\s.]+): (?P<month>{m:d})".format(m=currentMonth)
Run Code Online (Sandbox Code Playgroud)

顺便说一句,(?P<month>[1-12])可能未达到您的期望。正则表达式[1-12]匹配12仅匹配。如果要匹配一到十二,则需要(?P<month>12|11|10|[1-9])