【问题标题】:Python find string in URL after specific stringPython在特定字符串后的URL中查找字符串
【发布时间】:2021-11-05 11:05:53
【问题描述】:

我有这样的网址:

https://storage.cloud.google.com/test_bucket/first_test_user/0.jpg

使用 Python,我需要从中找到存储桶和 blob 值,以便分配变量:

bucket = 'test_bucket'
blob = 'first_test_user/0'

我想我需要正则表达式,但我无法在字符串中找到值。应该是这样的:

bucket = find(substring between 3rd and 4th "/")
blob = find(substring between 4th "/" and ".jpg")

非常感谢您的帮助,因为作为初学者,正则表达式对我来说真的很困惑..

【问题讨论】:

    标签: python regex string text-parsing


    【解决方案1】:
    import re
    
    txt = 'https://storage.cloud.google.com/test_bucket/first_test_user/0.jpg'
    bucket, blob = re.findall(r"//[^/]+.([^/]+).([^/]+)/", txt)[0]
    print(bucket, blob, sep='\n')
    

    或者,没有回复:

    txt = 'https://storage.cloud.google.com/test_bucket/first_test_user/0.jpg'
    s = txt.split('/')
    bucket, blob = s[3], s[4]
    print(bucket, blob, sep='\n')
    

    打印:

    test_bucket
    first_test_user
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2021-10-17
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多