0

I have a string:

x = "abc/xyz/foo/bar/foobar.mp3"

How to extract foobar out of it?

I have done it in this way:

import re
re.search(r'\/[a-z]+.mp3', x)

Although, I do not know how to extract the matched string without '.' and without '.mp3'.

I do not want to do Python splits, rplist, partition etc. as it adds extra functions. I want it to be as simple and short as possible.

EDIT:

  1. Yes, it is a path.
  2. I do not know the length of the path.
  3. As mentioned, I do not want to use splits.
naivepredictor
  • 898
  • 4
  • 14

2 Answers2

1

Match non-slashes, then lookahead for \.mp3$:

re.search(r'[^/]+(?=\.mp3$)', x)

Make sure to escape the . with a backslash, else it will match any character.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You can use this

[a-z]+(?=\.mp3$)
  • [a-z]+ - matches alphabets one or more time
  • (?=\.mp3$) - positive lookahead to check match must be followed by .mp3 and end of line

Demo

Code Maniac
  • 37,143
  • 5
  • 39
  • 60