rust 正则匹配多个 图片链接并下载本地封装函数调用

180it 2024-10-23 AM 123℃ 0条
[dependencies]
regex = "1.5.4"
reqwest = { version = "0.11", features = ["blocking", "json"] }

use regex::Regex;
use reqwest::blocking::get;
use std::fs::File;
use std::io::copy;
use std::io::Error;

fn download_images(text: &str) -> Result<(), Error> {
    // 正则表达式匹配图片链接
    let re = Regex::new(r"https://\S+\.(jpg|png|jpeg)").unwrap();

    // 遍历匹配到的链接
    for cap in re.captures_iter(text) {
        let url = &cap[0];
        println!("匹配到的图片链接: {}", url);

        // 下载图片
        let response = get(url).unwrap();
        let mut file = File::create(url.split('/').last().unwrap()).unwrap();
        copy(&mut response.bytes().unwrap().as_ref(), &mut file).unwrap();

        println!("图片已下载: {}", url.split('/').last().unwrap());
    }

    Ok(())
}

fn main() -> Result<(), Error> {
    // 示例文本
    let text = r#"
    https://xxxxx/1.jpg
    https://xxxxx/a4b.png
    https://xxxxx/4b.jpeg
    "#;

    // 调用下载图片的函数
    download_images(text)?;

    Ok(())
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

rust 正则匹配多个 图片链接并下载本地封装函数调用