How to get urls by regex c++?

I can't parse all url's from string. I want to push all url's to array.

#include <string>
#include <iostream>
#include <regex>

void checkString(std::string x,std::regex e){
  std::smatch m;
  std::regex_search (x,m,e);
  std::cout<<m.position(0);
}
void run(void){
    std::regex e("((https)|(http))\:\/\/media.discordapp.net\/.*\.(((png)|(gif))|((jpeg)|(jpg)))");

    std::string example="dadasdasdhttps://media.discordapp.net/Js1VPuxC5xs.pngdsdhttps://media.discordapp.net/Js1VPuxC5xs.gifsdhttps://media.discordapp.net/Js1VPuxC5xs.jpegsddshttps://media.discordapp.net/Js1VPuxC5xs.jpg";

    checkString(example,e);
}    

I expect the output of:
https://media.discordapp.net/Js1VPuxC5xs.png
https://media.discordapp.net/Js1VPuxC5xs.gif
https://media.discordapp.net/Js1VPuxC5xs.jpeg
https://media.discordapp.net/Js1VPuxC5xs.jpg

1 answer

  • answered 2019-07-10 22:23 Jarod42

    You might do:

    void checkString(std::string x,std::regex e){
        std::smatch m;
    
        while (regex_search(x, m, e))
        {
            std::cout << m.str() << '\n';
            x = m.suffix();
        }
    }
    
    int main(){
        std::regex e(R"((?:https|http):\/\/media\.discordapp\.net\/.*?\.(?:png|gif|jpeg|jpg))");
    
        std::string example="dadasdasdhttps://media.discordapp.net/Js1VPuxC5xs.pngdsdhttps://media.discordapp.net/Js1VPuxC5xs.gifsdhttps://media.discordapp.net/Js1VPuxC5xs.jpegsddshttps://media.discordapp.net/Js1VPuxC5xs.jpg";
    
        checkString(example,e);
    } 
    

    Demo