Search code examples
regexmetabase

regex: how to select first, second, third match


Sorry I am quite new with regex. I have items like:

"Cafes", "Footwear", "Women's fashion" 

I can select the 3 items: /".+?"/

The first item only : /^".+?"/

But what about the second, third item? What is the best way to match them?

Is there a generic way to select nth match in regex?

Many Thanks !

D


Solution

  • As I said, I'm unsure about Metabase's regex flavor. However, if it supports non-fixed-width lookbehind, you can use:

    (?<=                # Match something preceded by
      ^                 # the start of string
      (?:               # then
        "[^"]*",\x20    # a quoted string followed by a comma and a space
      ){n}              # n time
    )                   # 
    "[^"]*"             # where "something" is a quoted string.
    

    n can be 0 or any positive integer. The element matched will have an 1-based index of n + 1.

    Try it on regex101.com.

    In the case Metabase doesn't support that, you can also try your luck on PCRE's \K:

    ^                   # Match at the start of string
    (?:"[^"]*", ){n}    # n elements with commas
    \K                  # then forfeit everything we just matched
    "[^"]*"             # before matching a quoted string.
    

    Try it on regex101.com.