vim正则表达式搜索csv字符串并粘贴匹配项

时间:2009-05-05 16:30:41

标签: regex vim

编辑:

我需要有关在vim中使用正则表达式进行搜索的最佳方法的建议,并提取所发现的任何匹配项。


我有一个看起来像这样的csv文件:

两个字段:

  • ID

  • 描述


0g98932 “有时包含数字的长描述 1234567,或0000012345甚至BR00012345,但始终包含文本“

我需要搜索每一行的描述字段。 如果第二个字段中存在匹配 \ d {10} 的数字,我想将其拉出来。

:% s/(\d{10})/^$1/g这样的事情给了我一个

  

未找到模式(\ d {10})错误。

我从来没有学过如何从vim中的正则表达式搜索中获取和引用匹配 - 所以这是问题的一部分。

另一部分:

我真的很想。

  1. 删除除前7位 ID 以外的所有内容以及匹配项。
  2. id 和匹配项复制到另一个文件 - 或者复制到当前文件的顶部(某处 - 只是为了将匹配与未经过滤的数据分开)。

2 个答案:

答案 0 :(得分:6)

关于vim正则表达式的重要事项是不同的层次 正在逃避是必需的(而不是像Perl或Ruby中的正则表达式)

来自:help /\m

after:    \v     \m       \M        \V    matches
                 'magic'  'nomagic'
          $      $        $         \$    matches end-of-line
          .      .        \.        \.    matches any character
          *      *        \*        \*    any number of the previous atom
          ()     \(\)     \(\)      \(\)  grouping into an atom
          |      \|       \|        \|    separating alternatives
          \a     \a       \a        \a    alphabetic character
          \\     \\       \\        \\    literal backslash
          \.     \.       .         .     literal dot
          \{     {        {         {     literal '{'
          a      a        a         a     literal 'a'

默认设置是'magic',所以为了使你给的正则表达式有效,你就可以了 必须使用:

:%s/".*\(\d\{10}\).*"/\1/

如果要删除除前7位数字ID和匹配项以外的所有内容 (我假设你的意思是你想删除没有任何匹配的行)

:v/^\([[:alnum:]]\{7}\),\s*".*\(\d\{10}\).*/d
:%s//\1,\2/

:v/<pattern>/命令允许您在不匹配的每一行上运行命令 给定的模式,所以这只是删除不匹配。 :s//重用先前的模式, 所以我们不必指定它。

这改变了以下内容:

0g98932,"long description sometimes containing numbers like 0123456789"
0g98932,"long description no numbers"
0g98932,"long description no numbers"
0g98932,"long description sometimes containing numbers like 0123456789"
0g98932,"long description no numbers"
0g98932,"long description no numbers"
0g98932,"long description no numbers"
0g98932,"long description no numbers"
0g98932,"long description sometimes containing numbers like 0123456789"
0g98932,"long description no numbers"
0g98932,"long description no numbers"
0g98932,"long description sometimes containing numbers like 0123456789"

进入这个:

0g98932,0123456789
0g98932,0123456789
0g98932,0123456789
0g98932,0123456789

答案 1 :(得分:3)

要获取匹配,您必须使用

\(pattern\)

删除使用

:%s/not_pattern\(pattern\)another_not_pattern/\1/