user3090693
user3090693

Reputation: 1

Split csv-line by Regular Expression

Can you help me with parse some csv-line using regexp?
For example: 1,"2,3","2,3,""4""",,5

I need to get this array ['1' '2,3' '2,3,"4"' '' '5']

I tried to write this regexp. But its only split my line by separator ','.

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

I find this regexp, but its work incorrect with empty cell(,,)

(\s*'[^']+'|\s*[^,]+)(?=,|$)

Can you write me right regexp to parse any string?

Upvotes: 0

Views: 780

Answers (1)

Stephan
Stephan

Reputation: 43033

Here is the regex you are looking for:

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

Description

Regular expression visualization

Demo

https://www.debuggex.com/r/KVwn6W1zKG4tTXSI

Upvotes: 2

Related Questions