Home > Net >  Python / regex - Extract string between nth and nth character
Python / regex - Extract string between nth and nth character

Time:12-07

I have multiple url values, for ex:

https://www.happy.com/de/article/98238811/poppers

https://www.happy.com/sr

https://www.happy.com/en/forum/ocean-liveliness

I want to extract the values between the 3rd and 4th slash (if 4th slash exists) (ex: de, sr, en)

between the 4th and 5th slash (ex: article, forum)

I'm terrible at regex, I've tried this [\/]*[^\/] [\/]([^\/] ) but it seems to get all values including www.happy. which I don't want.

CodePudding user response:

In such case you might not even need regular expression. Just simply split the string by slash. And check the returned chunks. For example.

>>> "https://www.happy.com/de/article/98238811/poppers".split('/')[3]
'de'
>>> "https://www.happy.com/de/article/98238811/poppers".split('/')[4]
'article'

CodePudding user response:

I agree with the other answers/comments that Split function is easier, but if you insist on regex you have the \K operator in Python"s regex that discards the match portion to the left.

So, ^(?:.*?\/){3}\K.*?(?=\/|$) will search for three slashes from the beginning of each line, then discard it from the match, do a non-greedy match .*? to pick up the result you want, then do a lookahead to stop your match on a slash or end of line, whichever is encountered first. The lookahead will not be included in the match.

Make sure you include the RE.M flag if you are scanning multiple examples at once so ^ and $ match begin/end of line as well as begin/end of string.

  • Related