问题
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?
回答1:
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
回答2:
I don't know if it fits your needs, but you can search that way :
- Place your cursor at the beginning line
- Type 3 /
pattern
Return
It place the cursor on the 3rd occurrence of the next matching line (highlighting all occurrences)
You can also macro :
qa+3nq
then @a to go to the next line 3rd occurence
回答3:
For Google users (like me) that search just for: "regex nth occurrence". This will return position of last character of third 'foo' (you need to change {3}
to your n
and foo
to your text):
length(regexp_replace('lorem ifoopsum foo lor foor1 ipsum foo dolor foo', '((?:.*?foo){3}).*$', '\1'))
This: (?:.*?foo)
searches for anything followed by 'foo', then it is repeated 3 times (?:.*?foo){3}
, then string from start to (including) 3rd repetition is captured, then rest of string is matched by .*$
, then whole string is replaced by captured thing, and length of it is position of last character of 3rd 'foo'.
回答4:
Try this:
:Tabularize /^.\{-}\S\s\{2,}
Yes, Tabularize uses Vim's regex, so the example on Eelvex's answer should work.
来源:https://stackoverflow.com/questions/5422949/how-to-find-the-3rd-occurrence-of-a-pattern-on-a-line