如何在python中执行条件分割?

时间:2017-04-21 13:06:11

标签: python regex python-2.7

当逗号未被()包围时,我想用逗号分割字符串。

str = r"a,b,c,test(1,2,3),g,h,test(2,4,6)"

渴望分裂

split = ['a','b','c','test(1,2,3)','g','h','test(2,4,6)']

如何使用regex python

到目前为止我的努力,

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

3 个答案:

答案 0 :(得分:3)

如上所述,你可以使用负面看后面和前面的模式匹配。

import re

my_str = r"a,b,c,test(1,2,3),g,h,test(2,4,6)"

print(re.split('(?<!\(.),(?!.\))', my_str))

答案 1 :(得分:1)

您可以使用否定的lookbehind和负前瞻来查找未被括号,包围的所有)(

(?<![)(]),(?![)(])

以下是一个实例:https://regex101.com/r/uEyTN8/2

详情

  • (?<! )如果括号内的字符在下一次出现之前匹配,则会忽略下次出现的匹配
  • (?! )如果括号内的字符在出现后匹配,则会忽略此次出现的匹配
  • [)(]匹配括号

答案 2 :(得分:1)

不是正则表达式,但可能有效:

def my_split(s):

    splits0 = s.split(',')
    splits = []

    BEWEEN_PARENTHESIS = False

    # join everything between parenthesis
    for j, elem in enumerate(splits0):
        if not BEWEEN_PARENTHESIS:
            if "(" in elem:
                BEWEEN_PARENTHESIS = True
                start = j
            else:
                splits.append(elem)

        elif BEWEEN_PARENTHESIS and ")" in elem:

            BEWEEN_PARENTHESIS = False
            splits.append(",".join(splits0[start:j+1]))

    return splits

s = "a,b,c,test(1,2,3),g,h,test(2,4,6)"
print(my_split(s))