python - 用逗号分割字符串,除非在括号中

标签 python regex string

我想用逗号分割字符串,除非在括号中,但我的问题是当我有括号时

这是一个例子:

b='hi, this(me,(you)) , hello(a,b)'
re.split(r',(?![^\(]*[\)])', b)
['hi', ' this(me', '(you)) ', ' hello(a,b)']

我期望的是:

['嗨', '这个(我,(你))','你好(a,b)']

我见过与我想要的类似的问题,但它不像我期望的那样工作,我不知道为什么

1- Split string at commas except when in bracket environment

2- Python - Split by comma skipping the content inside parentheses

有什么帮助吗?

最佳答案

尝试使用模式(?!\S\)|\()

例如:

import re

b = ['hi, this(me,(you)) , hello(a,b)', 'hi, this(me,(you))']
for i in b:
    print(re.split(r',(?!\S\)|\()', i))

输出:

['hi', ' this(me,(you)) ', ' hello(a,b)']
['hi', ' this(me,(you))']

关于python - 用逗号分割字符串,除非在括号中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59660662/

相关文章:

python - 如何分隔接口(interface)名称

c - 字符串末尾的空字符 '\0'

c - 如何在 C 中分配和访问数组结构中的数据

python - 用Python绘制3D球体的最简单方法?

python - pandas.DataFrame.apply() 使用索引作为参数

python - 开罗:在 x 和 y 中绘制从 0 到 1 的空间中的所有内容,并且仅在最后重新缩放到特定分辨率(可调整大小的窗口)

java - 正则表达式检查IP

python - discord.py [mp3 @ 000001dc99bec540] 从比特率估计持续时间,这可能不准确

javascript - 如何替换宽度和高度形成像 'imagename-300x200.ext' 这样的字符串

Java Map 读取文件存储在 Map 中的第一个字母作为单词的键和值