Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Does the submatch Command Work In Vim?

I came across this really nifty and handy command

:.,$/^\d\+/\=submatch(0) + 1/g

What this does is it finds any line after the current line, and checks if that line begins with a number. If so, it will replace it with the increment of its current value; however, I'm quite confused with how this is actually happening. I am guessing that the \=submatch(0) portion is what is doing the heavy lifting, but I cant figure out how. There is also a + 1 after the submatch which is acting as arithmetic, which is surprising to me. I would have thought that it would be inserted as text instead of performing arithmetic on the matched number.

like image 621
Kalcifer Avatar asked Feb 20 '26 13:02

Kalcifer


1 Answers

Since the string starts with a \=, it is evaluated as an expression. In this case, submatch(0) + 1 is evaluated as a function.

submatch:

The whole matched text can be accessed with "submatch(0)". The text matched with the first pair of () with "submatch(1)". Likewise for further sub-matches in ().

In the regex above, the whole match is actually the digits (the first number on each matched line). So submatch(0) + 1 will add 1 to the captured match.

like image 76
Maroun Avatar answered Feb 23 '26 02:02

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!