【问题标题】:Avoid "rest of string" split results避免“其余字符串”拆分结果
【发布时间】:2016-10-20 02:31:43
【问题描述】:

我有这段代码可以将一个复杂的 CSV 文件拆分成多个块。难点是逗号也可能出现在“”中,因此不能将它们分开。我用来查找不在“”中的逗号的正则表达式工作正常:

comma_re = re.compile(r',(?=([^"]*""[^"]*"")*[^"]*$)')

演示:here

import re

test = 'Test1,Test2,"",Test3,Test4"",Test5'
comma_re = re.compile(r',(?=([^"]*""[^"]*"")*[^"]*$)')

print comma_re.split(test)

输出:

['Test1', 'Test2,"",Test3,Test4""', 'Test2', '"",Test3,Test4""', '"",Test3,Test4""', None, 'Test5']

期望:

['Test1', 'Test2', '"",Test3,Test4""', 'Test5']

如何避免无用的拆分结果?

编辑:我什至不知道默认的 CSV 模块,继续使用它。感谢您的努力!

【问题讨论】:

  • 试过 CSV 模块了吗?
  • 还没有,唯一困难的部分就是拆分,剩下的我要做的很简单......
  • 用正则表达式解析 csv 文件是个坏主意。只需使用为此构建的 csv 模块

标签: python regex csv split match


【解决方案1】:
(?<!"),(?![^",]+")|,(?=[^"]*$)

将适用于您提供的示例,但如果输入与该格式不同,它将不起作用。

input = 'Test1,Test2,"",Test3,Test4"",Test5'
output = re.split(r'(?<!"),(?![^",]+")|,(?=[^"]*$)', input)
print(output)

# ['Test1', 'Test2', '"",Test3,Test4""', 'Test5']

Python demo

您确实应该为此使用 CSV 解析器。如果由于某种原因你不能 - 只需进行一些手动字符串处理,逐个字符地检查并在看到逗号时拆分,除非你已经认识到你在一个带引号的字符串中。类似于以下内容:

input = 'Test1,Test2,"",Test3,Test4"",Test5'

insideQuoted = False
output = []
lastIndex = 0

for i in range(0, len(input)):
    if input[i] == ',' and not insideQuoted:
        output.append(input[lastIndex: i])
        lastIndex = i + 1
    elif input[i] == '"' and i < len(input) - 1 and input[i + 1] == '"':
        insideQuoted ^= True
    elif i == len(input) - 1:
        output.append(input[lastIndex: i + 1])

Demo

【讨论】:

    猜你喜欢
    • 2013-08-03
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    相关资源
    最近更新 更多