gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:49:36 25 4
gpt4 key购买 nike

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

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

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

最佳答案

使用字符串格式插入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]) .

关于python - 在正则表达式(python)中使用值为整数的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7354732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com