gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:45:39 25 4
gpt4 key购买 nike

编辑:

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


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

两个字段:

  • id

  • 描述


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

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

做类似 :% s/(\d{10})/^$1/g 的操作会给我一个

Pattern not found (\d{10}) error.

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

其他部分:

我真的很想。

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

最佳答案

了解 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

关于regex - vim 正则表达式搜索 csv 字符串并粘贴匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/825764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com