Java – when there are escape quotes or outside parentheses, separate commas outside the quotes
•
Java
Can I split strings using the following criteria?
for example
String source = "to_char(DATE,'YYYY,MM,DD'),'I am sad :(',to_char(DATE,('YYYY(MM,DD)')),('YYYY,DD')),NAME,'(YYYY)MM,CITY || ',(UK)',US''s CITY',UK'"; String[] expected = new String[]{ "to_char(DATE,DD')","'I am sad :('","to_char(DATE,DD)'))",// brackets within quotes within brackets "to_char(DATE,// missing open bracket in quotes "to_char(DATE,DD'))",// missing close bracket in quotes "NAME","CITY || ',(UK)'",US''s CITY'",// escape a single quote in quotes "CITY || ',UK'" }; String[] result = splitElements(source); assert expected.equals(result);
The first two points can be achieved by splitting on common outside quotes when escaped quotes exist
This is very useful when operating with SQL For example Split items, append, insert, pre items, etc
Thank you in advance
Solution
I know it's a little long, but it's quite direct. Just track how many parens and internal or external quotation marks
String[] splitElements(String source) { int parencount = 0; boolean q = false; List<String> l = new ArrayList<>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); switch (c) { case ',': if (!q && parencount == 0) { l.add(sb.toString()); sb.setLength(0); } else { sb.append(c); } break; case '(': if(!q) parencount++; sb.append(c); break; case ')': if(!q) parencount--; sb.append(c); break; case '\'': q = ! q; sb.append(c); break; default: sb.append(c); break; } } String last = sb.toString(); l.add(last); String sa[] = l.toArray(new String[l.size()]); return sa; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码