使用正则表达式提取文件名

时间:2018-05-09 04:15:08

标签: python regex

我想创建一个正则表达式来提取网址的文件名

https://example.net/img/src/img.jpg

我想提取img1.jpg

我使用python中的urlparse,但它以这种方式提取路径

img/src/img.jpg

如何使用正则表达式

提取文件名

2 个答案:

答案 0 :(得分:3)

使用class SearchReuseView: UICollectionReusableView { weak var delegate: SearchReuseDelegate? let adImageView: UIImageView = { let img = UIImageView() img.translatesAutoresizingMaskIntoConstraints = false img.contentMode = .scaleAspectFit return img }() override init(frame: CGRect) { super.init(frame: frame) self.setupViews() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.setupViews() } func setupViews() { backgroundColor = .black adImageView.isUserInteractionEnabled = true adImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap))) self.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: self.adImageView, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: self.adImageView, attribute: .right, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: self.adImageView, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: self.adImageView, attribute: .left, multiplier: 1, constant: 0)) addSubview(adImageView) } var item: Banner! { didSet { guard let img = item.img else {return} let url = URL(string: "\(img)") self.adImageView.kf.setImage(with: url, placeholder: nil, options: [.transition(ImageTransition.fade(1))], progressBlock: { (receivedSize, totalSize) in }) { (image, error, cacheType, imageURL) in if error != nil {} } } } @objc func handleTap(){ guard let link = item.link else { return } delegate?.didTapAds(link: link) } } 和否定索引

str.split

<强>输出:

url = "https://example.net/img/src/img.jpg"
print(url.split("/")[-1])

或使用img.jpg

os.path.basename

答案 1 :(得分:0)

如果您的网址格式是静态的,则可以使用正向前瞻

import re
pattern =r'\w+(?=\.jpg)'

text="""https://example.net/img/src/img.jpg
"""


print(re.findall(pattern,text)[0])

输出:

img