How to find the 3rd occurrence of a pattern on a line

Reman picture Reman · Mar 24, 2011 · Viewed 50.6k times · Source

Today I had to align a table at only the first multiple spaces on a line.

p.e.

<ScrollWheelDown>    move window     three lines     down  
<S-ScrollWheelDown>     move window    one page   down
<ScrollWheelUp>        move window      three lines up
<S-ScrollWheelUp>    move window   one page      up

I use Tabular plugin to align tables but I could not find a way how to find only the first occurrence of multiple spaces and do an align only there.

I don't know it either in VIM: What will be the regex if I only want to find the 3rd occurrence of a pattern on a line? Is the regex the same as using Tabular?

Answer

Eelvex picture Eelvex · Mar 24, 2011

The regex would be:

/\(.\{-}\zsPATTERN\)\{3}

So if, for example, you want to change the 3rd 'foo' to 'bar' on the following line:

lorem ifoopsum foo lor foor ipsum foo dolor foo
       ^1      ^2      ^3         ^4        ^5

run:

s/\(.\{-}\zsfoo\)\{3}/bar/

to get:

lorem ifoopsum foo lor barr ipsum foo dolor foo
       ^1      ^2      ^3=bar     ^4        ^5