简体   繁体   English

如何使用正则表达式将此字符串分为两部分?

[英]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') . 我试图使用re对其进行拆分,以便获得2个元素的数组,其中包含"('a','b','c')"('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. 我可以逐个字符地对其进行解析,但是如果可以使用正则表达式解决方案,我会更喜欢它。

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 看见

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, 之后, x将是('a', 'b', 'c') ,可以使用str(x)进行字符串化;如果空格很重要,

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

split is the wrong tool here. split是错误的工具。 You want findall : 您想要findall

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

or pretty much equivalently, 或者差不多

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM