Geo
Geo

Reputation: 96827

How can I split this string in two parts using a regex?

Imagine this:

a = "('a','b','c'),('d','e','f')"

I am trying to split it using re so that I will get an array of 2 elements, containing "('a','b','c')" and ('d','e','f'). I tried :

matches = re.split("(?:\)),(?:\()",a)

but this gives me the result:

'(2,3,4'
'1,6,7)'

I could parse it, character by character, but if a regex solution is possible, I would prefer it.

Upvotes: 2

Views: 115

Answers (3)

Amadan
Amadan

Reputation: 198324

split is the wrong tool here. You want findall:

import re
a = "('a','b','c'),('d','e','f')"
matches = re.findall("\([^)]*\)", a)

or pretty much equivalently,

matches = re.findall("\(.*?\)", a)

Upvotes: 2

codaddict
codaddict

Reputation: 455030

You need to split on the comma which is preceded by a ) and followed by a (. But the parenthesis themselves should not be part of the split point. For that you need to use positive lookahead and positive look behind assertions as:

matches = re.split("(?<=\)),(?=\()",a)

See it

Upvotes: 3

Fred Foo
Fred Foo

Reputation: 363587

Try this:

from ast import literal_eval
a = "('a','b','c'),('d','e','f')"
x, y = literal_eval(a)

After this, x will be ('a', 'b', 'c') which can be stringized with str(x), or, if spaces matter,

"(%s)" % ",".join(repr(z) for z in x)

Upvotes: 2

Related Questions