如何匹配此url的正则表达式?

2024-03-29 06:08:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个网址

http://download2142.mysite.com/d0kz4p5p3uog/api60w0g1o1jil1/upload.rar

“下载”之后的数字是随机生成的,而“下载”之后的两个目录我的网站'获取每个文件的随机字符串。你知道吗

我试过用(\.rar$)找到文件扩展名来下载文件,但问题是该页上还有其他链接的URL以.rar文件结尾,而不是实际的下载链接。因此,通过扩展查找下载链接在这里没有帮助。我需要下面这样的图案。你知道吗

http://download\[random_no_here\].mysite.com/\[randomstring_number_included here/\[another_randomstring_with_number_included_here/the_actual_file_here_with_random_name.rar


Tags: 文件comhttpnumberhere链接withrandom
1条回答
网友
1楼 · 发布于 2024-03-29 06:08:12

此正则表达式将执行您想要的操作:

r'http://download\d+\.mysite\.com/\w+/\w+/upload\.rar'

\d匹配数字,\w匹配字母数字(包括下划线);+表示匹配前面的一个或多个模式。我们在.com.rar前面使用\,这样.就被逐字解释,而不是作为regex通配符。你知道吗

测试

import re

p = re.compile(r'http://download\d+\.mysite\.com/\w+/\w+/upload\.rar')

table = [
    'http://download2142.mysite.com/d0kz4p5p3uog/api60w0g1o1jil1/upload.rar',
    'http://download2142.mysite.com/d0kz4p5p3uog/api60w0g1o1jil1/upload.raw',
    'http://download123.mysite.com/456/789/upload.rar',
    'http://downloadabc.mysite.com/def/ghi/upload.rar',
    'http://download1234.mysite.com/def/ghi/upload.rar',
    'http://download1234.mysite.org/def/ghi/upload.rar',
]

for s in table:
    m = p.match(s)
    print s, m is not None

输出

http://download2142.mysite.com/d0kz4p5p3uog/api60w0g1o1jil1/upload.rar True
http://download2142.mysite.com/d0kz4p5p3uog/api60w0g1o1jil1/upload.raw False
http://download123.mysite.com/456/789/upload.rar True
http://downloadabc.mysite.com/def/ghi/upload.rar False
http://download1234.mysite.com/def/ghi/upload.rar True
http://download1234.mysite.org/def/ghi/upload.rar False

如果实际文件名不同,则可以使用

r'http://download\d+\.mysite\.com/\w+/\w+/\w+\.rar'

或者

r'http://download\d+\.mysite\.com/\w+/\w+/[a-z]+\.rar'

如果名称总是小写字母


顺便说一句,它通常是not a good idea to parse HTML with regex,但是如果页面格式是固定的,并且相当简单,那么您就可以摆脱它。你知道吗

相关问题 更多 >