I have a requirement in Python that I need to replace all the commas with a unique character, such as "$"
or "|"
, using regular expression. I tried doing so but not able to achieve my objective.
Please find below a sample string where I need to replace.
For eg consider the string below :-
SELECT 'column1' AS "Column 1" ,
'column2' AS "Column 2" ,
'column3' AS "Column 3",
SUM(Column_1, Column_2) , 'column5' AS "Column 5" ,
CONCAT("str1","str2","str3") ,
ADD(len(str1),avg(column_1),sum(column_1,column_2,column_3))
In the above string i want to replace all the commas inside parentheses with "$" ie
SUM(Column_1 $ Column_2)
CONCAT("str1"$"str2"$"str3")
ADD(len(str1)$avg(column_1)
$sum(column_1$column_2$column_3))
I have to do this with the help of regular expressions. I was able to do this for 2 values, means that when there is only one comma inside the ( ) I was able to replace but when tested with the scenario of more than one comma, my expression failed.
A regex like this? (\\s?,\\s?)(?=[^\\(]*\\))|(\\s?,\\s?)(?=(?:[^\\(]*\\([^\\(]*?\\))*\\))
see: https://regex101.com/r/uT1gQ7/3
It matches the comma with optional spaces around it, if it is followed by )
before another (
appears, using lookahead , looking at level 1 deepness. The second alternative looks if the remaining string has an aditional )
besides other (stuff)
structures, It should do the trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.