使用 vim 正则表达式删除引号之间的所有逗号

remove all commas between quotes with a vim regex

我有一个 CSV 文件,其中包含以下行:

57,13,"Bob, Bill and Susan",Student,Club,Funded,64,3200^M

我需要它们看起来像

57,13,Bob-Bill-and-Susan,Student,Club,Funded,64,3200

我正在使用 vim 正则表达式。我将其分为 4 个步骤:

  1. 删除 ^M 并插入换行符:

    :%s:<ctrl-V><ctrl-M>:\r:g`
    
  2. 将所有</code>替换为<code>-:

    :%s: :\-:g
    
  3. 删除引号之间的逗号:需要帮助。

  4. 删除引号:

    :%s:\"\([^"]*\)\"::g
    

如何删除引号之间的逗号,而不删除文件中的所有逗号?

是这样的吗?

:%s:\("\w\+\),\(\w\+"\): :g

:%s:\("\w*\)\(,\)\(.*"\)::g 删除逗号

我对此问题的首选解决方案(删除引用区域内的逗号)是使用表达式替换,而不是尝试在一个正则表达式中完成此操作。

为此,您需要在替换前添加 \=,以便将替换视为 vim 表达式。从这里您可以只提取引号之间的部分,然后分别处理匹配的部分。这需要有两个简短的正则表达式,而不是一个复杂的正则表达式。

:%s/".\{-}"/\=substitute(submatch(0), ',', '' , 'g')/g

所以 ".\{-}" 匹配引号中的任何内容(非贪婪)并且 substitute(submatch(0), ',', '' , 'g') 获取匹配的内容并删除所有逗号,其 return 值用作实际替换。

相关的帮助页面是:help sub-replace-special


至于你问题的其他部分。第 1 步实质上是尝试删除所有回车符 return,因为文件格式实际上是 dos 文件格式。您可以使用 dos2unix 程序删除它们。

在第 2 步中,替换中的 - 转义是不必要的。所以命令只是

:%s/ /-/g

在第 4 步中,如果您只想删除引号,那么您的正则表达式过于复杂。因为您需要做的就是匹配引号并删除它们

:%s/"//g
:%s:\("\w*\)\(,\)\(.*"\)::g

示例:"this is , an, example"

\("\w*\) match start of " every letter following qoutes group  for back reference
\(,\) capture comma group  for back reference
(.*"\) match every other character upto the second qoute ->group 3 for backreference
:: only include groups without comma, discard group 2 from returned string which is