tags:

views:

1187

answers:

4

I know, now I have two problems. But I'm having fun!

I started with this advice not to try and split, but instead to match on what is an acceptable field, and expanded from there to this expression.

final Pattern pattern = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?=,|$)");

The expression looks like this without the annoying escaped quotes:

"([^"]*)"|(?<=,|^)([^,]*)(?=,|$)

This is working well for me - either it matches on "two quotes and whatever is between them", or "something between the start of the line or a comma and the end of the line or a comma". Iterating through the matches gets me all the fields, even if they are empty. For instance,

the quick, "brown, fox jumps", over, "the",,"lazy dog"

breaks down into

the quick
"brown, fox jumps"
over
"the"

"lazy dog"

Great! Now I want to drop the quotes, so I added the lookahead and lookbehind non-capturing groups like I was doing for the commas.

final Pattern pattern = Pattern.compile("(?<=\")([^\"]*)(?=\")|(?<=,|^)([^,]*)(?=,|$)");

again the expression is:

(?<=")([^"]*)(?=")|(?<=,|^)([^,]*)(?=,|$)

Instead of the desired result

the quick
brown, fox jumps
over
the

lazy dog

now I get this breakdown:

the quick
"brown
 fox jumps"
,over,
"the"
,,
"lazy dog"

What am I missing?

+4  A: 

Operator precedence. Basically there is none. It's all left to right. So the or (|) is applying to the closing quote lookahead and the comma lookahead

Try:

(?:(?<=")([^"]*)(?="))|(?<=,|^)([^,]*)(?=,|$)
Devon_C_Miller
Ah, I see. So I should be trying to group the quote stuff together, and also the comma stuff. Unfortunately enclosing the quote stuff in (?: ) didn't seem to have any effect. I tried adding it to the comma stuff too, and also just grouping both of them in another set of parentheses, none of which had any effect. I will continue to hunt for the correct syntax; if I find it before someone else posts it I'll give you the answer.
Nathan Spears
A: 

When I started to understand what I had done wrong, I also started to understand how convoluted the lookarounds were making this. I finally realized that I didn't want all the matched text, I wanted specific groups inside of it. I ended up using something very similar to my original RegEx except that I didn't do a lookahead on the closing comma, which I think should be a little more efficient. Here is my final code.

package regex.parser;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CSVParser {

    /*
     * This Pattern will match on either quoted text or text between commas, including
     * whitespace, and accounting for beginning and end of line.
     */
    private final Pattern csvPattern = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?:,|$)"); 
    private ArrayList<String> allMatches = null; 
    private Matcher matcher = null;
    private String match = null;
    private int size;

    public CSVParser() {  
     allMatches = new ArrayList<String>();
     matcher = null;
     match = null;
    }

    public String[] parse(String csvLine) {
     matcher = csvPattern.matcher(csvLine);
     allMatches.clear();
     String match;
     while (matcher.find()) {
      match = matcher.group(1);
      if (match!=null) {
       allMatches.add(match);
      }
      else {
       allMatches.add(matcher.group(2));
      }
     }

     size = allMatches.size();  
     if (size > 0) {
      return allMatches.toArray(new String[size]);
     }
     else {
      return new String[0];
     }   
    } 

    public static void main(String[] args) {  
     String lineinput = "the quick,\"brown, fox jumps\",over,\"the\",,\"lazy dog\"";

     CSVParser myCSV = new CSVParser();
     System.out.println("Testing CSVParser with: \n " + lineinput);
     for (String s : myCSV.parse(lineinput)) {
      System.out.println(s);
     }
    }

}
Nathan Spears
I feel like I should re-iterate that this was just for my entertainment, is not guaranteed to work, and certainly WILL NOT work if you try to enclose escaped delimiters inside one of your fields. Use the opensource java csv libraries on sourceforge or wherever that is if you need something "real".
Nathan Spears
A: 

I know this isn't what the OP wants, but for other readers, one of the String.replace methods could be used to strip the quotes from each element in the result array of the OPs current regex.

Tim Bender
That's true too.
Nathan Spears
A: 

thanks for the above code!

lawrence
If you like it, vote up the answer!
Nathan Spears