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

后端 未结 4 2207
囚心锁ツ
囚心锁ツ 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: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'.

提交回复
热议问题