不考虑方括号中的逗号

不考虑方括号中的逗号

本文介绍了以逗号分隔的分隔字符串,不考虑方括号中的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串

I've got a string like

s="abc, 3rncd (23uh, sdfuh), 32h(q23q)89 (as), dwe8h, edt (1,wer,345,rtz,tr t), nope";

我想将其拆分为那些字符串

and I want to split it into those string

String[] parts={"abc", "3rncd (23uh, sdfuh)", "32h(q23q)89 (as)", "dwe8h", "edt (1,wer,345,rtz,tr t)", "nope"};

如果我只是调用 s.split(,"),那么修整后我会得到不同的结果,因为在某些字符串中,例如"3rncd(23uh,sdfuh)"仍然有一个逗号.但是我不想在方括号中加逗号.有解决这个问题的优雅方法吗?

If I simply call s.split(",") then after trimming I would get a different result because in some of those string, for example "3rncd (23uh, sdfuh)" there is still a comma. But I don't want to could commas in brackets. Is there an elegant way to solve that problem?

推荐答案

假定()不嵌套也不转义.您可以使用以下方式进行拆分:

Assuming ( and ) are not nested and unescaped. You can use split using:

String[] arr = input.split(",(?![^()]*\\))\\s*");

RegEx演示

,(?![^()] * \))将与逗号匹配,如果它后面没有非括号文本和),则忽略()中的逗号.

,(?![^()]*\)) will match a comma if it is NOT followed by a non-parentheses text and ), thus ignoring commas inside ( and ).

这篇关于以逗号分隔的分隔字符串,不考虑方括号中的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 05:22