Regex for changing :variable to ${variable} in sql query

zljubisic at gmail.com zljubisic at gmail.com
Wed Apr 18 16:04:58 EDT 2018


On Wednesday, 18 April 2018 19:34:37 UTC+2, MRAB  wrote:
> > Hi,
> > 
> > I have a sql query in which all variables declared as :variable should be changed to ${variable}.
> > 
> > for example this sql:
> > 
> > select *
> > from table
> > where ":x" = "1" and :y=2
> > and   field in (:string)
> > and   time between :from and  :to
> > 
> > 
> > should be translated to:
> > 
> > select *
> > from table
> > where "${x}" = "1" and ${y} = 2
> > and   field in ( ${string} )
> > and   time between ${from} and ${to}
> > 
> > As far as I have come is to find the group as (:(.+?)\b)
> > and than replace it as ${$2}
> > 
> > (it would be nice if before and after the ${variable} it is always one space)
> > 
> > For opposite change (from ${variable} notation to :variable) I am using:
> > 
> > sql.replace('${', ':').replace('}', '')
> > 
> > Can someone please help?
> > 
> Try this:
> 
> new_query = re.sub(r':([a-z][a-z0-9_]*)', r'${\1}', query)
> 
> To convert the other way, try this:
> 
> new_query = re.sub(r'\$\{([a-z][a-z0-9_]*)\}', r':\1', query)

Thanks a lot.
Regards.



More information about the Python-list mailing list