Postgresql - Regex split csv line with potentials quotes

前端 未结 1 623
情话喂你
情话喂你 2021-01-21 16:27

I would like to split a column that represent a csv line in postgres. Fields in this text line are delimited by pipe, sometime they are enclosed by quote and sometime not. In ad

相关标签:
1条回答
  • 2021-01-21 16:42

    Not about regexp but it works

    create or replace function split_csv(
      line text,
      delim_char char(1) = ',',
      quote_char char(1) = '"')
    returns setof text[] immutable language plpythonu as $$
      import csv
      return csv.reader(line.splitlines(), quotechar=quote_char, delimiter=delim_char, skipinitialspace=True, escapechar='\\')
    $$;
    
    select *, x[4] from split_csv('field1|"field2"|field3|"22 \" lcd \| screen "'||E'\n'||'a|b', delim_char := '|') as x;
    
    ╔══════════════════════════════════════════════╤════════════════════╗
    ║                      x                       │         x          ║
    ╠══════════════════════════════════════════════╪════════════════════╣
    ║ {field1,field2,field3,"22 \" lcd | screen "} │ 22 " lcd | screen  ║
    ║ {a,b}                                        │ ░░░░               ║
    ╚══════════════════════════════════════════════╧════════════════════╝
    
    0 讨论(0)
提交回复
热议问题