Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to select first five CSVs from a string

Tags:

java

regex

I have a CSV string like apple404, orange pie, wind\,cool, sun\\mooon, earth, in Java. To be precise each value of the csv string could be any thing provided commas and backslash are escaped using a back slash.

I need a regular expression to find the first five values. After some goggling I came up with the following. But it wont allow escaped commas within the values.

Pattern pattern = Pattern.compile("([^,]+,){0,5}");
Matcher matcher = pattern.matcher("apple404, orange pie, wind\\,cool, sun\\\\mooon, earth,");
    if (matcher.find()) {
        System.out.println(matcher.group());
    } else {
        System.out.println("No match found.");
    }

Does anybody know how to make it work for escaped commas within values?

like image 536
Thomas Avatar asked Sep 01 '26 17:09

Thomas


1 Answers

Following negative look-behind based regex will work:

 Pattern pattern = Pattern.compile("(?:.*?(?<!(?:(?<!\\\\)\\\\)),){0,5}");

However for full fledged CSV parsing better use a dedicated CSV parser like JavaCSV.

like image 177
anubhava Avatar answered Sep 04 '26 07:09

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!