Cloud
Cloud

Reputation: 19333

regex breakdown for "find and replace nth occurrence"

I'm analyzing a regex pattern I found on a separate question on the VI SE site, and I'm having trouble breaking it down, i.e.:

\(.\{-}\zsPATTERN\)\{N}

How does this pattern do a replace operation on the Nth occurrence of PATTERN (i.e. could someone please help me expand the logic in this regex)?

Thank you.

Upvotes: 2

Views: 118

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

Here, the pattern matches N occurrences of a sequence of any 0+ chars, as few as possible, omitting this sequence and then matching the PATTERN.

That is:

  • \( - start of a grouping construct
  • .\{-} - any 0+ chars, as few as possible
  • \zs - omits the text matched so far
  • PATTERN - some PATTERN
  • \) - end of the grouping construct
  • \{N} - a range / limiting quantifier, repeating the group pattern(s) N times.

Upvotes: 2

Related Questions