全局子匹配()?

发布于 2024-12-19 18:10:37 字数 242 浏览 3 评论 0原文

我想找到一行,然后匹配该行中的几个单词,但我不想替换它们,而是更愿意简单地保存它们(通过附加到寄存器或导出到文件)。

在这方面,反向引用(即 submatch(1) 或 \1)是否可行,或者只能通过替换?我意识到我可以替换回我正在处理的文件 - 更改它 - 但我更愿意导出它。

有没有办法在替换中调用函数(以保存子匹配)而不损坏文件?或者,最好使用全局搜索来捕获该行的一部分,然后将其作为参数传递给函数调用,该函数调用将根据需要进行保存?

I wanted to find a line, then match several words within that line BUT instead of substituting them I would prefer to simply save them (by appending to a register, or exporting to a file).

Is back-referencing (i.e. submatch(1) or \1) doable in this regards, or is that only through the substitution? I realize I could substitute back to the file I am working on - altering it - but I would prefer to export it.

Is there a way to call a function (to save the submatch) within substitute without damaging the file? Or, preferably, use the global search to capture a portion of the line and then pass that as a parameter onto a function call that would do the saving as desired?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吲‖鸣 2024-12-26 18:10:37

尝试

:%s/pattern \(saved portion\)/\=[submatch(0), SaverFunc(submatch(1))][0]/

:%s/pattern \(saved portion\)\zs/\=SaverFunc(submatch(1))[-1]

。在最后一种情况下,SaverFunc 必须返回字符串或数字(如果没有显式 :return 语句,它将返回数字 0)。返回哪个字符串或数字并不重要:string_or_number[-1] 始终扩展为空字符串。

Try

:%s/pattern \(saved portion\)/\=[submatch(0), SaverFunc(submatch(1))][0]/

or

:%s/pattern \(saved portion\)\zs/\=SaverFunc(submatch(1))[-1]

. In last case SaverFunc must return either string or number (without explicit :return statement it will return number 0). It does not matter which string or number will be returned: string_or_number[-1] always expands to an empty string.

吃不饱 2024-12-26 18:10:37

您可能正在寻找 :h :global 并执行如下操作:

:g/pattern/call func_to_get_and_save_text()

这将在与给定模式匹配的每一行上调用该函数。

You might be looking for :h :global and do something like this:

:g/pattern/call func_to_get_and_save_text()

That would call the function on every line matching the given pattern.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文