This sample data is returned by Web Service
200,6, “California, USA”
I want to split them using split(",") and tried to see the result using simple code.
String loc = "200,6,\"California, USA\"";
String[] s = loc.split(",");
for(String f : s)
System.out.println(f);
Unfortunately this is the result
200
6
"California
USA"
The expected result should be
200
6
"California, USA"
I tried different regular expressions and no luck. Is it possible to escape the given regular expression inside of "" ?
UPDATE 1: Added C# Code
UPDATE 2: Removed C# Code
This is the regex you want
(To put it in the split function you’ll need to escape the quotes in the string)
Explanation
You need to find all ‘,’s not in quotes..
That is you need lookahead (http://www.regular-expressions.info/lookaround.html) to see whether your current matching comma is within quotes or out.
To do that we use lookahead to basically ensure the current matching ‘,’ is followed by an EVEN number of ‘”‘ characters (meaning that it lies outside quotes)
So
(?:[^"]|"[^"]*")*$means match only when there are non quote characters till the end OR a pair of quotes with anything in between them(?=(?:[^"]|"[^"]*")*$)will lookahead for the above match,(?=(?:[^"]|"[^"]*")*$)and finally this will match all ‘,’ with the above lookahead