Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex: find and replace commas between quotation marks

Tags:

python

regex

I have a string,

line = '12/08/2013,3,"9,25",42:51,"3,08","12,9","13,9",159,170,"3,19",437,'

and I would like to find and replace the commas, between quotation marks, with ":". Looking for a results

line = '12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,'

So far I have been able to match this pattern with,

import re
re.findall('(\"\d),(.+?\")', line)

however, I guess I should be using

re.compile(...something..., line)
re.sub(':', line)

Does anyone know how to do this? thanks, labjunky

like image 767
labjunky Avatar asked Feb 15 '23 11:02

labjunky


1 Answers

>>> import re
>>> line = '12/08/2013,3,"9,25",42:51,"3,08","12,9","13,9",159,170,"3,19",437,'
>>> re.sub(r'"(\d+),(\d+)"', r'\1:\2', line)
'12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,'

\1, \2 refer to matched groups.


Non-regex solution:

>>> ''.join(x if i % 2 == 0 else x.replace(',', ':')
            for i, x in enumerate(line.split('"')))
'12/08/2013,3,9:25,42:51,3:08,12:9,13:9,159,170,3:19,437,'
like image 54
falsetru Avatar answered Apr 27 '23 19:04

falsetru