Vim:如果 submatch(1) 为空,则删除与模式匹配的文本 [英] Vim: Delete the text matching a pattern IF submatch(1) is empty

查看:56
本文介绍了Vim:如果 submatch(1) 为空,则删除与模式匹配的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此命令行解析联系人列表文档,该文档可能包含或不包含电话、电子邮件或网络列表.如果它具有所有三个,那么一切都很好 - 在行尾附加来自 FormatContact() 的返回以进行数据上传:

This command line parses a contact list document that may or may not have either a phone, email or web listed. If it has all three then everything works great - appending the return from the FormatContact() at the end of the line for data uploading:

silent!/^\d/+1|ki|/\n^\d\|\%$/-1|kj|'i,'jd|let @a = substitute(@",'\s*Phone: \([^,]*\)\_.*','\1',"")|let @b = substitute(@",'^\_.*E-mail:\s\[\d*\]\([-_@.0-9a-zA-Z]*\)\_.*','\1',"")|let @c = substitute(@",'^\_.*Web site:\s*\[\d*\]\([-_.:/0-9a-zA-Z]*\)\_.*','\1',"")|?^\d\+?s/$/\=','.FormatContact(@a,@b,@c)

或者,分解:

silent!/^\d/+1|ki|/\n^\d\|\%$/-1|kj|'i,'jd
let @a = substitute(@",'\s*Phone: \([^,]*\)\_.*','\1',"")
let @b = substitute(@",'^\_.*E-mail:\s\[\d*\]\([-_@.0-9a-zA-Z]*\)\_.*','\1',"")
let @c = substitute(@",'^\_.*Web site:\s*\[\d*\]\([-_.:/0-9a-zA-Z]*\)\_.*','\1',"")
?^\d\+?s/$/\=','.FormatContact(@a,@b,@c)

我创建了三个单独的搜索,以便在一个原子匹配失败时不会使任何一个搜索失败,因为 - 再次 - 每个联系人的联系信息可能存在也可能不存在.

I created three separate searches so as not to make any ONE search fail if one atom failed to match because - again - the contact info may or may not exist per contact.

问题 解决方案创建的问题是,当模式不匹配时,我将整个 @" 放入 @a.相反,当匹配不发生时,我需要它为空.我需要每个变量表示(电话、电子邮件、网络)是否为空.

The Problem that solution created was that when the pattern does not match I get the whole @" into @a. Instead, I need it to be empty when the match does not occur. I need each variable represented (phone,email,web) whether it be empty or not.

  1. 我没有看到可以在替换函数中设置的标志会这样做.
  2. 如果 \1 为空,有没有办法返回 ""?
  3. 有没有办法创建一个可选原子,以便搜索查询仍然可以考虑空匹配,以便将其正确记录为空?

推荐答案

代替使用替换来替换整个捕获的文本对于感兴趣的部分,只能匹配该目标部分.不像替换例程,匹配的要么定位文本符合到给定的模式,或报告没有这样的文本.因此,使用 matchstr() 函数优先于 substitute(),问题中列出的解析代码可以更改如下:

Instead of using substitutions that replace the whole captured text with its part of interest, one can match only that target part. Unlike substitution routines, matching ones either locate the text conforming to the given pattern, or report that there is no such text. Thus, using the matchstr() function in preference to substitute(), the parsing code listed in the question can be changed as follows:

let @a = matchstr(@", '\<Phone:\s*\zs[^,]*')
let @b = matchstr(@", '\<E-mail:\s*\[\d*\]\zs[-_@.0-9a-zA-Z]*')
let @c = matchstr(@", '\<Web site:\s*\[\d*\]\zs[-_.:/0-9a-zA-Z]*')

这篇关于Vim:如果 submatch(1) 为空,则删除与模式匹配的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆