How to extract values within a quotation from a string using regex? [duplicate]
How about this? The idea is to split the last group into 2 groups.
Pattern p = Pattern.compile("(\\w+)=\"([^\"]+)\"|([^\\s]+)");
String test = "a0=d235 a1=2314 com1=\"abcd\" com2=\"a b c d\"";
Matcher m = p.matcher(test);
while(m.find()){
System.out.print(m.group(1));
System.out.print("=");
System.out.print(m.group(2) == null ? m.group(3):m.group(2));
System.out.println();
}
Update
Here is a new solution in response to the updated question. This regex applies positive look-ahead and look-behind to make sure there is a quote without actually parsing it. This way, groups 2 and 3 above, can be put in the same group (group 2 below). There is no way to exclude the quotes by while returning group 0.
Pattern p = Pattern.compile("(\\w+)=\"*((?<=\")[^\"]+(?=\")|([^\\s]+))\"*");
String test = "a0=d235 a1=2314 com1=\"abcd\" com2=\"a b c d\"";
Matcher m = p.matcher(test);
while(m.find()){
print m.group(1);
print "="
println m.group(2);
}
Output
a0=d235
a1=2314
com1=abcd
com2=a b c d