簡體   English   中英

如何使用正則表達式在python中進行復雜的替換?

[英]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_mapstr.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM