How to match between the nth occurrence and nth +1 occurrence using regex


I have the following text:


I would like to extract what is between the 2nd occurrence of / and the 3rd occurrence of /. Based on the text, the following will be extracted


So far I came out with this pattern ‘S+?/’ which gives me 3 matches. That it, whats behind each /. I only want to depend on the slashes.

Asked By: Sarah cartenz




>>> s='aBcD-19/WES/VA-MKL-2217223/2020'

You can do:

>>> s.split('/')[2]

Or with a regex:

Answered By: dawg

Here is a method that returns a string part between 2nd and third "/" (if there are more than two "/" characters in the string. Otherwise returns the string itself.

def find_string():
    my_str = "aBcD-19/WES/a"
    slices = my_str.split('/')
    if (len (slices)) > 2:
        return slices[2]
    return my_str
Answered By: Subhash Prajapati
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.