Sizor
Sizor

Reputation: 19

String split by commas but skip one comma

i have this string:

"O2TV, SportTV", Netflix /603605506, 2016-01-02 15:15:01

I need split it into array[3] by commas, but skip comma in quotation marks. Is there any simple way, like one split command? Thanks!

Upvotes: 0

Views: 718

Answers (2)

ProgrammerBoy
ProgrammerBoy

Reputation: 891

If you want to skip all occurrences of comma in double quotes then you can refer below solution,

public class Sample {

    private static final String REGEX = ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";

    public static void main(String[] args) {
        String inputString = "\"O2TV, SportTV\", Netflix /603605506, 2016-01-02 15:15:01";
        String[] tokens = inputString.split(REGEX, -1);

        for (String token : tokens) {
            System.out.println(token);
        }
    } }

Upvotes: 0

tantalum
tantalum

Reputation: 2452

It really depends on exactly what you want.

If you want to always skip the first comma you can do something like

String firstSection = csvString.substring(0, csvString.indexOf(","));
String[] remainingParts = csvString.substring(csvString.indexOf(",", csvString.indexOf(","))).split(",");

On the other had, if you want to skip any commas inside quotes, then you need a full on CSV parser.

Upvotes: 1

Related Questions