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

后端 未结 4 2204
囚心锁ツ
囚心锁ツ 2020-12-05 15:10

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

p.e.

    move window     three lines     down  
<         


        
相关标签:
4条回答
  • 2020-12-05 15:27

    Try this:

    :Tabularize /^.\{-}\S\s\{2,}
    

    Yes, Tabularize uses Vim's regex, so the example on Eelvex's answer should work.

    0 讨论(0)
  • 2020-12-05 15:33

    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
    
    0 讨论(0)
  • 2020-12-05 15:39

    I don't know if it fits your needs, but you can search that way :

    1. Place your cursor at the beginning line
    2. 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

    0 讨论(0)
  • 2020-12-05 15:43

    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'.

    0 讨论(0)
提交回复
热议问题