使用Regex从URL中提取文件名 - 需要排除一些字符

问题描述 投票:-4回答:3

我有一个格式如下的资源:

{"url": "http://res1.icourses.cn/share/process17//mp4/2017/3/17/6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4", "name": "1-课程导学"}, 
{"url": "http://res2.icourses.cn/share/process17//mp4/2017/3/17/a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4", "name": "2-计算机网络的定义与分类"}

我想从网址中提取文件名6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4

如何编写正则表达式以匹配此位置的字符串?

python regex python-3.x
3个回答
0
投票

你可以使用re.findall

import re
s = [{"url": "http://res1.icourses.cn/share/process17//mp4/2017/3/17/6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4", "name": "1-课程导学"}, {"url": "http://res2.icourses.cn/share/process17//mp4/2017/3/17/a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4", "name": "2-计算机网络的定义与分类"}]
filenames = [re.findall('(?<=/)[\w\-\_]+\.mp4', i['url'])[0] for i in s]

输出:

['6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4', 'a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4']

0
投票

根据您提供的字符串,您可以迭代字典,获取“url”的值并使用以下正则表达式

([^\/]*)$

说明:

() - defines capturing group
[^\/] - Match a single character not present after the ^
\/ - matches the character / literally (case sensitive)
* - Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ - asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

例如:

for record in records:
    print(re.search("([^\/]*)$", record['url']).group(1))

在这种情况下,我们正在利用文件名出现在字符串末尾的事实。使用$锚点使唯一有效的匹配终止字符串。

如果要对作为字符串强制转换的字典执行此操作,可以通过更改结束条件。像所以([^\/]*?)\",。现在",终止比赛(注意\逃脱"。请参阅https://regex101.com/r/k9VwC6/25

最后,如果我们不是那么幸运,捕获组在字符串的末尾(意味着我们不能使用$),我们可以使用负面的背后。你可以阅读那些here


0
投票

你可以使用短的正则表达式[^/]*$

码:

import re
s = [{"url": "http://res1.icourses.cn/share/process17//mp4/2017/3/17/6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4", "name": "1-课程导学"}, {"url": "http://res2.icourses.cn/share/process17//mp4/2017/3/17/a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4", "name": "2-计算机网络的定义与分类"}]
filenames = [re.findall('[^/]*$', i['url'])[0] for i in s]
print(filenames)`

输出:

['6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4','a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4']

检查正则表达式 - https://regex101.com/r/k9VwC6/30

© www.soinside.com 2019 - 2024. All rights reserved.