使用一个变量,其值是正则表达式中的整数(python)

时间:2011-09-08 21:29:14

标签: python regex

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

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

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

2 个答案:

答案 0 :(得分:4)

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

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

顺便说一下,(?P<month>[1-12])可能没有达到预期效果。正则表达式[1-12]仅匹配12。如果你想匹配一到十二, 你需要(?P<month>12|11|10|[1-9])

答案 1 :(得分:0)

我不知道你在搜索什么,所以我无法测试,但尝试:

(r"(?P<speaker>[A-Za-z\s.]+): (?P<month>%r)" % currentMonth, foo)

其中foo是您正在使用表达式的字符串。