Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string based on commas between words with special conditions - Python

Tags:

python

regex

My problem is this, there is a string

[word in IN ('hello', 'world'), key1=1100, key2=1200]

I need a list that would contain

[word in IN ('hello', 'world'),
 key1=1100,
 key2=1200
]

Obviously splitting by comma doesn't work, so went with regular expression grouping.

pattern= re.compile(r"(.*), [a-zA-Z]?", re.DOTALL)
string = "[word in IN ('hello', 'world'), key1=1100, key2=1200]"
for item in re.findall(pattern, string):
    print item

What I am trying to do is to match only the commas after which space and an alphabet would occur, but for me, it giving wrong results.

[word in IN ('hello', 'world'), key1=1100

Still, it's greedy matching. Any help would be appreciated.

like image 980
sysuser Avatar asked Mar 25 '26 13:03

sysuser


1 Answers

You could do re.split() with a positive lookahead:

In [3]: re.split(r", (?=[a-zA-Z])", s)
Out[3]: ["[word in IN ('hello', 'world')", 'key1=1100', 'key2=1200]']
like image 148
alecxe Avatar answered Mar 27 '26 02:03

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!