繁体   English   中英

用逗号分割字符串,括号中除外

[英]Split string by commas except when in bracket

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

这是一个例子:

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

我期望的是:

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

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

1- 以逗号分隔字符串,括号环境中除外

2- Python - 通过逗号跳过括号内的内容进行拆分

有什么帮助吗?

尝试使用模式(?!\\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))']

如果主要文本组都用逗号和空格分隔,那么您可以使用re.split

import re
b='hi, this(me,(you)) , hello(a,b)'
result = re.split(',\s', b)

输出:

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

但是,您也可以使用递归来解析字符串:

def parse(d):
  if (v:=next(d, None)) is not None and v != ')':
     yield v if v != '(' else f'({"".join(parse(d))})'
     yield from parse(d)

r, c, l = list(filter(lambda x:x != ',', parse(iter(re.findall('\w+|\(|\)|,', b))))), '', []
for i in r:
   if not i.endswith(')'):
      l.append(c)
      c = i
   else:
      l.append(c+i)
      c = ''

l.append(c)
final_result = list(filter(None, l))

输出:

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

没有正则表达式的方法可能是这样的:

b='hi, this(me,(you))'

phrase = ''
phrases = []

in_parenth = 0

for l in b:

    if l == '(':
        in_parenth += 1
    elif l == ')':
        in_parenth -= 1

    if l == ',' and in_parenth == 0:
        if phrase.strip():
            phrases.append(phrase)
        phrase = ''
    else:
        phrase += l

if phrase.strip():
    phrases.append(phrase)

print(phrases)

暂无
暂无

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

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