Reputation: 96827
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
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
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)
Upvotes: 3
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