[英]Using Regex to extract file name from URL -- need to exclude some characters
我有一个格式如下的资源:
{"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-计算机网络的定义与分类"}
我想从 url 中提取文件名6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4
和a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4
。
我将如何编写正则表达式来匹配此位置的字符串?
根据您提供的字符串,您可以遍历字典,获取“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
最后,如果我们不是很幸运,捕获组位于字符串的末尾(这意味着我们不能使用$
),我们可以使用负向后面。 你可以在这里阅读这些内容。
您可以使用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']
您可以使用简短的正则表达式[^/]*$
代码:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.