在Python中用字符串替换正则表达式变量
我遇到了一种情况,我有一个正则表达式,像这样:
regex_string = r'(?P<x>\d+)\s(?P<y>\w+)'
r = re.compile(regex_string)
在我开始用这个正则表达式匹配东西之前,我想把名为 x
的正则表达式组替换成一个特定的值,比如2014。这样,当我用这个正则表达式去找匹配的内容时,我们只会找到那些 x=2014
的情况。有什么好的方法来解决这个问题吗?
这里的挑战是,原始的正则表达式 regex_string
和要替换的值 x=2014
都是由最终用户指定的。在我看来,理想的情况是有一个像 replace_regex
这样的函数:
r = re.compile(regex_string)
r = replace_regex_variables(r, x=2014)
for match in r.finditer(really_big_string):
do_something_with_each_match(match)
我对任何解决方案都持开放态度,但特别想了解是否可以做到这一点 而不 在 finditer
返回结果后再检查匹配,以便利用 re
的性能。换句话说,最好不要这样做:
r = re.compile(regex_string)
for match in r.finditer(really_big_string):
if r.groupdict()['x'] == 2014:
do_sometehing_with_each_match(match)
1 个回答
0
你想要的就是这个,对吧?
r = r'(?P<x>%(x)s)\s(?P<y>\w+)'
r = re.compile(r % {x: 2014})
for match in r.finditer(really_big_string):
do_something_with_each_match(match)