Split a string with custom delimiter, respect and preserve quotes (single or double)

前端 未结 2 1521
予麋鹿
予麋鹿 2021-01-29 10:04

I have a string which is like this:

>>> s = \'1,\",2, \",,4,,,\\\',7, \\\',8,,10,\'
>>> s
\'1,\",2, \",,4,,,\\\',7, \\\',8,,10,\'
2条回答
  •  忘掉有多难
    2021-01-29 10:41

    It looks like you are reinventing python module csv. Batteries included.

    In [1]: import csv
    In [2]: s = '1,",2, ",,4,,,\',7, \',8,,10,'
    In [3]: next(csv.reader([s]))
    Out[3]: ['1', ',2, ', '', '4', '', '', "'", '7', " '", '8', '', '10', '']
    

    I think, regexp's often are not good solution. It can be surprisingly slow in unexpected moments. In csv module can adjust dialect and it's easy to process any numner of strings/file.

    I've failed to adjust csv to two variants of quotechar at the same time, but do you really need it?

    In [4]: next(csv.reader([s], quotechar="'"))
    Out[4]: ['1', '"', '2', ' "', '', '4', '', '', ',7, ', '8', '', '10', '']
    

    or

    In [5]: s = '1,",2, ",,4,,,",7, ",8,,10,'
    In [6]: next(csv.reader([s]))
    Out[6]: ['1', ',2, ', '', '4', '', '', ',7, ', '8', '', '10', '']
    

提交回复
热议问题