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

Question:

I have the following text:

aBcD-19/WES/VA-MKL-2217223/2020

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

VA-MKL-2217223

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

||

Answers:

Given:

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

You can do:

>>> s.split('/')[2]
'VA-MKL-2217223'

Or with a regex:

>>> re.search(r'(?:[^/]+/){2}([^/]+)',s).group(1)
'VA-MKL-2217223'
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.