I want to split string with comma when comma is not surrounded by ().
str = r"a,b,c,test(1,2,3),g,h,test(2,4,6)"
Desired split
split = ['a','b','c','test(1,2,3)','g','h','test(2,4,6)']
how can I do using regex python
My efforts so far,
splits = [m.start() for m in re.finditer(',', string_i)]
paranths = {10: 16, 26: 32} #using function
lst = []
first = 1
for l in splits:
print l
for m in paranths:
if (l < m and l < paranths[m]):
#print m,':',l,':',paranths[m]
lst.append(string_i[first:l])
first = l+1
break
break
As said above you can use negative look behind and ahead pattern matching.
import re
my_str = r"a,b,c,test(1,2,3),g,h,test(2,4,6)"
print(re.split('(?<!\(.),(?!.\))', my_str))
You can use a negative lookbehind and a negative lookahead to find all , which are not surrounded by a bracket )(.
(?<![)(]),(?![)(])
Here is a live example: https://regex101.com/r/uEyTN8/2
Details:
(?<! ) if the characters inside the parenthesis match before the next occurence, it will dismiss the match of the next occurrence(?! ) if the characters inside the parenthesis match after the occurence, it will dismiss the match of this occurrence[)(] match parenthesisIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With