简体   繁体   中英

How do I omit certain parts of a string with python's re?

I have this string:

url = '/justicefor/404/1nirmala5.jpg'

I want to extract it as 404.jpg . I tried something like:

pattern = re.compile(
         r"./justicefor/(\d+/.\.\w+)",
         re.IGNORECASE
    )

But this selects the text between 404 and jpg too. How do I fix this?

I'm new to regular expressions so

Here is a solution,

Regex Demo

import re

re.sub("/justicefor/(.*)/.*(\.\w+)", r"\1\2", "/justicefor/404/1nirmala5.jpg")

'404.jpg'

You can use the os module

Ex:

import os

url = '/justicefor/404/1nirmala5.jpg'

path, ext = os.path.splitext(url)
print(os.path.basename(os.path.dirname(path)) + ext)  #--> 404.jpg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM