Link to home
Start Free TrialLog in
Avatar of Envoy2064
Envoy2064

asked on

How to split columns with exceptions

Hi,
   Can anyone help me with this problem:

How can I split CSV file in Java (into separate columns), using built-in regex functions (for efficiency), but ignore everything in double quotes? So:

1,2,3,"hello, world!"

will be treated as 4 columns, not 5.
Avatar of ddrudik
ddrudik
Flag of United States of America image

If you won't have empty columns you could do something like:

import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Module1{
  public static void main(String[] asd){
  String sourcestring = "source string to match with pattern";
  Pattern re = Pattern.compile("""[^""]*""|[^,]+");
  Matcher m = re.matcher(sourcestring);
    if(m.find()){
      for( int groupIdx = 0; groupIdx < m.groupCount(); groupIdx++ ){
        System.out.println( "[" + groupIdx + "] = " + m.group(groupIdx));
      }
    }
  }
}

Open in new window

Avatar of Envoy2064
Envoy2064

ASKER

How about with empty columns?
Please note the emphasis on efficient algorithms that uses as much system-optimized code as possible.
ASKER CERTIFIED SOLUTION
Avatar of ddrudik
ddrudik
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the question and the points.