4

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])"

2 Answers 2

5

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]).

Sign up to request clarification or add additional context in comments.

11 Comments

I'd use {m:d} to leave no chance for strings that might break the regex in weird ways to be passed.
@Rosh Oxymoron: Hm, nice idea.
@unutbu (?P<month>[2-9]|1[012]?) better imho
@eyquem: Just curious -- why do you consider it better? It's less readable and also slower for even moderate-sized strings.
@unutbu Because, afaiu and shortly, with (?P<month>12|11|10|[1-9]) the regex motor will have to perform 4 tests to identify a digit 1 to 9 and 1 or 3 tests to identify one of the numbers 12-11-10, while with (?P<month>[2-9]|1[012]?) it will perform only one test to identify a digit 2 to 9 and 3 tests to identify a number 1 or 10 or 11 or 12. But I know that regex motors are optimized, and I'm maybe wrong
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.