[英]how to do a complex replace in python using regex?
Here is the scenario: 这是场景:
dict = {'t1': 'm1', 'year': '2003'}
pattern = re.compile(r'#\{(.*?)\}')
str = "select * from records where year = #{year} and t1 = #{t1}"
What I want to do is to replace the str
to "select * from records where year = 2003 and t1 = m1" 我想做的是将
str
替换为“从year = 2003和t1 = m1的记录中选择*”
Could anyone tell me how to do it using python regex? 谁能告诉我如何使用python正则表达式吗? Thanks!
谢谢!
If you use {..}
instead of #{..}
, you can use str.format_map
or str.format
: 如果您使用
{..}
而不是#{..}
,则可以使用str.format_map
或str.format
:
>>> d = {'t1': 'm1', 'year': '2003'}
>>> fmt = "select * from records where year = {year} and t1 = {t1}"
>>> fmt.format_map(d) # available only in Python 3.2+
'select * from records where year = 2003 and t1 = m1'
>>> fmt.format(**d)
'select * from records where year = 2003 and t1 = m1'
Regular expression solution: Use re.sub
with the replacement function as the second argument. 正则表达式解决方案:将
re.sub
与替换函数一起用作第二个参数。
>>> d = {'t1': 'm1', 'year': '2003'}
>>> fmt = "select * from records where year = #{year} and t1 = #{t1}"
>>> import re
>>> re.sub(r'#\{(.*?)\}', lambda m: d[m.group(1)], fmt) # m -> match object
'select * from records where year = 2003 and t1 = m1'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.