[英]how to do a complex replace in python using regex?
這是場景:
dict = {'t1': 'm1', 'year': '2003'}
pattern = re.compile(r'#\{(.*?)\}')
str = "select * from records where year = #{year} and t1 = #{t1}"
我想做的是將str
替換為“從year = 2003和t1 = m1的記錄中選擇*”
誰能告訴我如何使用python正則表達式嗎? 謝謝!
如果您使用{..}
而不是#{..}
,則可以使用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'
正則表達式解決方案:將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.