正则表达式,用于在CSV文件中查找和替换未转义的非连续双引号

时间:2010-07-05 16:03:04

标签: regex programming-languages csv expression

这是对相关问题的扩展 Here

我有一个需要解析的每周csv文件。它看起来像这样。

"asdf","asdf","asdf","asdf"

但有时会有一些文本字段包含一个额外的未转义的双引号字符串,如此

"asdf","as "something" df","asdf","asdf"

从这里的其他帖子,我能够整理一个正则表达式

(?m)""(?![ \t]*(,|$))

匹配两个连续的双引号,只有“如果它们之前没有逗号或行尾,可选空格和制表符”

现在这只会连续发现双引号。如何修改它以查找和替换/删除文件中“某事”周围的双引号?

感谢。

3 个答案:

答案 0 :(得分:6)

(?<!^|,)"(?!,|$)

将匹配一个双引号,该双引号前面或后面没有逗号,也不在行的开头/结尾。

如果你需要在逗号周围或开头/结尾处允许空格,并且你的正则表达式(你没有指定)允许任意长度的lookbehind(例如,.NET),你可以使用

(?<!^\s*|,\s*)"(?!\s*,|\s*$)

答案 1 :(得分:3)

我使用VIM删除.CSV文件中的嵌套引号,这对我有用:

"[^,"][^"]*"[^,]

答案 2 :(得分:0)

在vim中,我用它来删除所有未转义的引号。

:%s/\v("(,")@!)&((",)@<!")&("(\n)@!)&(^@<!")//gc

详细解释是,

: - start the vim command
    % - scope of the command is the whole file
    s - search and replace
        / - start of search pattern
        \v - simple regex syntax (rather than vim style)
            (
                " - double quote
                (,") - comma_quote
                @! - not followed by
            )
            & - and
            (
                (",) - quote_comma
                @<!- does not precedes
                " - double quote
            )
            & - and
            (
                " - double quote
                (\n) - line end
                @! - not followed by
            )
            & - and
            (
                ^ - line beginning
                @<! - does not precedes
                " - double quote
            )
        / - end of search pattern and start of replace pattern
             - replace with nothing (delete)
        / - end of replace pattern
    g - apply to all the matches
    c - confirm with user for every replacement

这很快就完成了这项工作。唯一失败的实例是数据中存在“,”模式的实例。