[英]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
.我想将其提取为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.但这也会选择404和jpg之间的文本。 How do I fix this?我该如何解决?
I'm new to regular expressions so我是正则表达式的新手,所以
Here is a solution,这是一个解决方案,
import re
re.sub("/justicefor/(.*)/.*(\.\w+)", r"\1\2", "/justicefor/404/1nirmala5.jpg")
'404.jpg'
You can use the os
module您可以使用os
模块
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.