拆分由逗号分隔的字符串,不考虑括号中的逗号 [英] Split string delimited by comma without respect to commas in brackets

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

问题描述

我有一个类似的字符串

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*");

正则表达式演示

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆