[Practical.Vim(2012.9)].Drew.Neil.Tip94 學習摘要

來源:互聯網
上載者:User

標籤:數字   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 學習摘要

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.