Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"};

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
310 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

RegEx Demo

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...