python - 如何在 python 中执行条件拆分?

标签 python regex python-2.7

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

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

期望的 split

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

我如何使用正则表达式 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

最佳答案

如上所述,您可以使用负向后视模式匹配。

import re

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

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

关于python - 如何在 python 中执行条件拆分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43543523/

相关文章:

python - 使用负索引在 Python 中访问整个字符串

django - 导入错误 : No module named local

python - 有效的 XPath 表达式

python - 如何通过操作更改 Tkinter 中框的背景颜色

python - 类型错误 : 'psycopg2._psycopg.Binary' object does not support indexing

java - 在“>”上分割长字符串

regex - 匹配至少一个小写字母和至少一个大写字母

java - 正则表达式中下划线字符的含义

python - 有效地找到实体计数 Google App Engine

python - scipy 插值速度 : Is there anything faster than RectBivariateSpline?