繁体   English   中英

用逗号分割字符串,但忽略括号内的逗号

[英]Split string by comma, but ignore commas within brackets

我正在尝试使用 python 以逗号分隔字符串:

s = "year:2020,concepts:[ab553,cd779],publisher:elsevier"

但我想忽略方括号 [] 中的任何逗号。 所以上面的结果是:

["year:2020", "concepts:[ab553,cd779]", "publisher:elsevier"]

有人对如何执行此操作有建议吗? 我试着像这样使用 re.split:

params = re.split(",(?![\w\d\s])", param)

但它不能正常工作。

result = re.split(r",(?!(?:[^,\[\]]+,)*[^,\[\]]+])", subject, 0)
,                 # Match the character “,” literally
(?!               # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   (?:               # Match the regular expression below
      [^,\[\]]          # Match any single character NOT present in the list below
                           # The literal character “,”
                           # The literal character “[”
                           # The literal character “]”
         +                 # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
      ,                 # Match the character “,” literally
   )
      *                 # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   [^,\[\]]          # Match any single character NOT present in the list below
                        # The literal character “,”
                        # The literal character “[”
                        # The literal character “]”
      +                 # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   ]                 # Match the character “]” literally
)

更新以支持括号中的 2 个以上的项目。 例如

year:2020,concepts:[ab553,cd779],publisher:elsevier,year:2020,concepts:[ab553,cd779,xx345],publisher:elsevier

您可以使用用户定义的 function 而不是拆分来解决此问题:

s = "year:2020,concepts:[ab553,cd779],publisher:elsevier"


def split_by_commas(s):
    lst = list()
    last_bracket = ''
    word = ""
    for c in s:
        if c == '[' or c == ']':
            last_bracket = c
        if c == ',' and last_bracket == ']':
            lst.append(word)
            word = ""
            continue
        elif c == ',' and last_bracket == '[':
            word += c
            continue
        elif c == ',':
            lst.append(word)
            word = ""
            continue
        word += c
    lst.append(word)
    return lst
main_lst = split_by_commas(s)

print(main_lst)

上述代码运行结果:

['year:2020', 'concepts:[ab553,cd779]', 'publisher:elsevier']

此正则表达式适用于您的示例:

,(?=[^,]+?:)

在这里,我们使用正向前瞻来查找逗号,后跟非逗号和冒号字符,然后是冒号。 这会正确找到您正在搜索的<comma><key>模式。 当然,如果允许键有逗号,则必须进一步调整。

你可以在这里查看正则表达式

使用仅具有前瞻的模式来断言右侧的字符,如果左侧有伴随字符,则不会断言。

除了使用拆分之外,您还可以匹配方括号之间的 1 个或多个重复值,或者匹配除逗号之外的任何字符。

(?:[^,]*\[[^][]*])+[^,]*|[^,]+

正则表达式演示

s = "year:2020,concepts:[ab553,cd779],publisher:elsevier"
params = re.findall(r"(?:[^,]*\[[^][]*])+[^,]*|[^,]+", s)
print(params)

Output

['year:2020', 'concepts:[ab553,cd779]', 'publisher:elsevier']

我采用了@Bemwa 的解决方案(不适用于我的用例)

def split_by_commas(s):
    lst = list()
    brackets = 0
    word = ""
    for c in s:
        if c == "[":
            brackets += 1
        elif c == "]":
            if brackets > 0:
                brackets -= 1
        elif c == "," and not brackets:
            lst.append(word)
            word = ""
            continue
        word += c
    lst.append(word)
    return lst

暂无
暂无

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

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