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.
3
  • 1
    print(os.path.splitext(os.path.basename(x)))? Commented May 28, 2019 at 8:06
  • (it's a duplicate assume it's a file path. Given the .mp3 I'd think that it is) Commented May 28, 2019 at 8:06
  • x.split("/")[-1].split(".")[0] Commented May 28, 2019 at 8:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.