variables in a regular expression

Asked 1 years ago, Updated 1 years ago, 40 views

Cannot use variable in regular expression.
I would like to add up the dates for a particular month, but the following would not work.

month=input()
re.findall(r'month/([0-9]{1,2}), data)

What should I do?

python python3 regular-expression

2022-09-29 22:21

1 Answers

A string of month in the regular expression is expected to be the cause of the failure.
Try rewriting the month using the format function, as shown in the code below.

import re
Enter month=input()//"01"

data=""01/30
01/AA
02/20""" 

print(r'month/([0-9]{1,2}')#month/({0-9]{1,2}) is printed
If pattern='{}/([0-9]{{{1,2}}}' .format(month)#r'', {{and}} will be converted to {and}
re.findall(pattern,data)#['30']

If it still doesn't work, please add an error message.


2022-09-29 22:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.