Regex for changing :variable to ${variable} in sql query
MRAB
python at mrabarnett.plus.com
Wed Apr 18 13:34:19 EDT 2018
On 2018-04-18 08:25, zljubisic at gmail.com 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)
More information about the Python-list
mailing list