標籤:數字 vim
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
執行這個命令得到
[Practical.Vim(2012.9)].Drew.Neil.Tip94 學習摘要