开发者

Python / regex - Extract string between nth and nth character

I have multiple url values, for ex:

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

https://www.happy.com/sr

https开发者_如何学JAVA://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.


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'


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜