[Practical.Vim(2012.9)].Drew.Neil.Tip94 学习摘要

Perform Arithmetic on the Replacement

假设我们有一个文档如下
这里写图片描述

We want to promote each heading, turning <h2> into <h1>, <h3> into <h2>, and so on
我们打算把每一个heading 比如 <h2>转为 <h1>,数字降低1.

Here ’s the general idea: we write a pattern that matches the numeral portion of HTML header tags. Then we write a substitute command that uses a Vim script expression to subtract one from the number that was captured.
一般的方法如下:我们写一个pattern匹配文件中HTML的头tag,然后再用substitute命令,通过vim 脚本把找到的数字减去1.

The Search Pattern

The only thing that we want to change is the numeral part of the header tags, so ideally we want to create a pattern that matches that and nothing else. We don ’t want to match all digits. We only want to match the ones that immediately follow <h or </h. This pattern should do the trick:
我们想改变的是head tag中的数字,所以我们要创建一个pattern只匹配到这个而不是其他的数字。我们要匹配直接跟在<h</h后面的数字。pattern如下

 /\v\<\/?h\zs\d

The \zs item allows us to zoom in on part of the match. To simplify our example, we could say that a pattern of h\zs\d would match the letter “h ” followed by any digit ( “h1, ” “h2,” and so on). The placement of \zs indicates that the “h” itself would be excluded from the match, even though it is an integral part of the broader pattern (we met the \zs item in Tip 77,, where we compared it to Perl’s positive lookbehind assertion).

\zs可以让我们更加精确的定位到match的某个部分。简单的说h\zs\d 可以匹配跟在h后面的任何数字。采用\zs意味着h从match结果中排除掉了,尽管h是pattern的组成部分。\zs表示match开始,\ze表示match结束(在Tip77中有详细描述)。
同时注意这里\<\/ 对<和/进行了转置,如果不对/进行转置,那么会把这个/作为pattern的终止,只搜索<.
?表示0或1个字符或数字

The Substitute Command

We want to perform arithmetic inside the replacement field of our substitute command. To do this, we ’ll have to evaluate a Vim script expression. We can fetch the current match by calling the submatch(0) function. Since our search pattern matched a digit and nothing else, we can expect that submatch(0) will return a number. From this, we subtract one and return the result to be substituted in place of the match.
This substitute command should work:
我们打算在substitute命令中执行算术运算,就要采用vim script表达式,用 \=来引入。我们可以通过调用submatch(0)来获取当前的匹配。由于我们的搜索只匹配出了数字,所以我们可以期望submatch(0)返回数字,然后可以减去1,把这个值替换match.

:%s//\=submatch(0)-1/g

执行这个命令得到
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值