假设我在Python中有以下正则表达式,我想使用变量而不是[1-12]
。例如,我的变量是currentMonth = 9
如何将currentMonth插入正则表达式?
r"(?P<speaker>[A-Za-z\s.]+): (?P<month>[1-12])"
答案 0 :(得分:4)
使用字符串格式化将currentMonth
插入正则表达式模式:
r"(?P<speaker>[A-Za-z\s.]+): (?P<month>{m:d})".format(m=currentMonth)
顺便说一下,(?P<month>[1-12])
可能没有达到预期效果。正则表达式[1-12]
仅匹配1
或2
。如果你想匹配一到十二,
你需要(?P<month>12|11|10|[1-9])
。
答案 1 :(得分:0)
我不知道你在搜索什么,所以我无法测试,但尝试:
(r"(?P<speaker>[A-Za-z\s.]+): (?P<month>%r)" % currentMonth, foo)
其中foo
是您正在使用表达式的字符串。