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

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

java - Split string delimited by comma without respect to commas in brackets

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

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

1 Answer

0 votes
by (71.8m points)

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 ).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...