Single Regex to extract a/b/c from a/b/c/d:Z1234 and a/b/c from a/b/c:Y5678

Viewed 33

I have data apple/banana/orange/cherries:Z1234 and avocado/cantaloupe/watermelon:Y5678

How to put single regex that can get apple/banana/orange and avocado/cantaloupe/watermelon ?

If I put r'(.+?/.+?/.+?):.* I get avocado/cantaloupe/watermelon but I will get apple/banana/orange/cherries (the goal is supposed to be only apple/banana/orange)

If I put r'(.+?/.+?/.+?)/.* I get apple/banana/orange but I will get avocado/cantaloupe/watermelon:Y5678 (the goal is supposed to be only avocado/cantaloupe/watermelon)

How can I solve it with single regex?

2 Answers

You seem to be looking for parts that don't contain slashes or colons, so [^/:]+/[^/:]+/[^/:]+.

Use

[^/:\s]+(?:/[^/:\s]+){2}

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  [^/:\s]+                 any character except: '/', ':', whitespace
                           (\n, \r, \t, \f, and " ") (1 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (2 times):
--------------------------------------------------------------------------------
    /                        '/'
--------------------------------------------------------------------------------
    [^/:\s]+                 any character except: '/', ':',
                             whitespace (\n, \r, \t, \f, and " ") (1
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  ){2}                     end of grouping
Related