开发者

using a variable whose value is an integer in a regular expression (python)

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])"
开发者_C百科


Use string formating to insert currentMonth into the regex pattern:

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

By the way, (?P<month>[1-12]) probably does not do what you expect. The regex [1-12] matches 1 or 2 only. If you wanted to match one through twelve, you'd need (?P<month>12|11|10|[1-9]).


I dont know what you're searching through so I can't test this but try:

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

where foo is the string you're using the expression on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜