Search code examples
regexregexp-replace

Find specific char inside delimiter


I have this string:

(40.959953710949506, -74.18210638344726),(40.95891663745299, -74.10606039345703),(40.917472246121065, -74.09582940498359),(40.921752754230255, -74.16397897163398),(40.95248644043785, -74.21067086616523)

I need to grab the commas inside the parentesis for further processing, and I want the commas spliting the groups to remain.

Let's say I want to replace the target commas by FOO, the result should be:

(40.959953710949506 FOO -74.18210638344726),(40.95891663745299 FOO -74.10606039345703),(40.917472246121065 FOO -74.09582940498359),(40.921752754230255 FOO -74.16397897163398),(40.95248644043785 FOO -74.21067086616523)

I want a Regular Expression that is not language specific.


Solution

  • For example:

    import re
    
    s = "(40.959953710949506, -74.18210638344726),(40.95891663745299, -74.10606039345703),(40.917472246121065, -74.09582940498359),(40.921752754230255, -74.16397897163398),(40.95248644043785, -74.21067086616523)"
    s = re.sub(r",(?=[^()]+\))", " FOO", s)
    print(s)
    
    # (40.959953710949506 FOO -74.18210638344726),(40.95891663745299 FOO -74.10606039345703),(40.917472246121065 FOO -74.09582940498359),(40.921752754230255 FOO -74.16397897163398),(40.95248644043785 FOO -74.21067086616523)
    

    We use a positive lookahead to only replace commas where ) comes before ( ahead in the string.