[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如下
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
執行這個命令得到
總結
以上是生活随笔為你收集整理的[Practical.Vim(2012.9)].Drew.Neil.Tip94 学习摘要的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python mse函数_Python
- 下一篇: 软件工程2019:第2次作业—— 时事点