这是对Here回答的相关问题的扩展
我有一个需要解析的每周csv文件。它看起来像这样。
"asdf","asdf","asdf","asdf"
但有时会有一些文本字段包含一个额外的未转义的双引号字符串
"asdf","as "something" df","asdf","asdf"
从这里的其他帖子,我能够整理一个正则表达式
(?m)""(?![ \t]*(,|$))
它匹配两个连续的双引号,只有“如果它们之前没有逗号或行尾,可选中间有空格和制表符”
现在这只能连续找到双引号。如何修改它以查找和替换/删除文件中“something”周围的双引号?
谢谢。
(?<!^|,)"(?!,|$)
将匹配一个双引号,该引号不在逗号之前或之后,也不在逗号的开头/结尾。
如果你需要允许逗号周围或开始/结束时的空格,并且你的正则表达式(你没有指定)允许任意长度的lookbehind(例如.NET),你可以使用
(?<!^\s*|,\s*)"(?!\s*,|\s*$)
我使用VIM删除.CSV文件中的嵌套引号,这对我有用:
"[^,"][^"]*"[^,]
在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
这很快就完成了工作。唯一失败的实例是数据中存在“,”模式的实例。