【问题标题】:i want to find a specific peiece of data from a string using python regular expresion and exclude specific portion我想使用 python 正则表达式从字符串中查找特定的数据并排除特定部分
【发布时间】:2021-11-25 21:58:12
【问题描述】:
((http(s?):)./([a-z]).*/)这是正则表达式试试
但在这个字符串中,我想要这样的目录:/wp-content/uploads/2021/09/
图片名称如下:VideoHive-Happy-Kids-Slideshow-Premiere-Pro-MOGRT-Free-Download-GetintoPC.com_-300x169.jpg
【问题讨论】:
标签:
regex
web-scraping
regular-language
【解决方案1】:
您可以使用 2 个捕获组
https?:\/\/[^/]*(\/wp-content\/uploads\/\d{4}\/\d{2}\/)([^\/\s]+)
-
https?:\/\/[^/]* 将协议匹配到第一个 / 之前
-
( 捕获第 1 组
-
\/wp-content\/uploads\/\d{4}\/\d{2}\/ 匹配 /wp-content/uploads/ 4 位 / 2 位 /
-
)关闭第一组
-
([^\/\s]+) 捕获 第 2 组,匹配除 / 或空白字符以外的任何字符 1 次以上
Regex demo
const s = `https://getintopc.com/wp-content/uploads/2021/09/VideoHive-Happy-Kids-Slideshow-Premiere-Pro-MOGRT-Free-Download-GetintoPC.com_-300x169.jpg https://getintopc.com/wp-content/uploads/2021/09/VideoHive-Happy-Kids-Slideshow-Premiere-Pro-MOGRT-Direct-Link-Free-Download-GetintoPC.com_-300x169.jpg https://getintopc.com/wp-content/uploads/2021/09/VideoHive-Happy-Kids-Slideshow-Premiere-Pro-MOGRT-Full-Offline-Installer-Free-Download-GetintoPC.com_-300x169.jpg https://getintopc.com/wp-content/uploads/2021/09/VideoHive-Happy-Kids-Slideshow-Premiere-Pro-MOGRT-Latest-Version-Free-Download-GetintoPC.com_-300x169.jpg`;
const regex = /https?:\/\/[^/]*(\/wp-content\/uploads\/\d{4}\/\d{2}\/)([^\/\s]+)/g;
const res = Array.from(s.matchAll(regex), m => [m[1], m[2]]);
console.log(res);
或者更广泛的版本,首先匹配以[a-z] 开头的文件夹,然后是以数字开头并以.jpg 结尾的文件夹
https?:\/\/[^/]*((?:\/[a-z][^/]*)+(?:\/\d+)+\/)([^\/]+\.jpg)
Regex demo
【解决方案2】:
你可以试试这个:
https?:\/\/.*?(?<folder>\/.*?\/.*?\/.*?\/.*?\/)(?<image>.*)
我添加了两个捕获组,分别是文件夹和图像的名称。