1

I'am trying to parse a CSV but the column names contain new lines and I'am struggling to find a proper solution.

If I have the following csv header for example:

"Column 1 \n(this has valuable info)","Column 2","Column 3" \n 

and I split by the new line character it will take in account the new line within the quotes as well causing the whole header to be split into multiple lines.

Is there a way that I can ignore the \n characters in double quotes with a regex? The ones that I've tried by searching in Google threw the 'Regex too complicated' error.

1 Answer 1

1

This expression gets you close:

((?:")([^"]*)(?:")|[^,]*)(?:,|$)

I was mostly worried about intervening commas when I wrote it. So it doesn't quite handle the real end of line properly. Might require only minor tweaks to take you the rest of the way, though, so I provide it here as a starting point.

Demo:

String headerLine = '"Column 1 \n(this has valuable info)","Column 2","Column 3" \n ';
Matcher m = Pattern.compile('((?:")([^"]*)(?:")|[^,]*)(?:,|$)').matcher(headerLine);
while (m.find()) system.debug('Header: ' + m.group());

Log:

USER_DEBUG [3]|DEBUG|Header: "Column 1
USER_DEBUG (this has valuable info)",
USER_DEBUG [3]|DEBUG|Header: "Column 2",
USER_DEBUG [3]|DEBUG|Header: "Column 3"

USER_DEBUG [3]|DEBUG|Header:

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .