3

I'm trying to parse a URL with regex, and I've created the regex below:

std::regex r("https?://[0-9a-zA-Z.]+(:([0-9]+))?.*", std::regex_constants::extended);

(I'm trying to get the port out of the URL)

I can't seem to match any URL, but the regex works on several online regex testers for any URL. As a test, I created some much simpler code to check, which I can't get to match either.

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

int main() {
    std::string str = "http";
    std::smatch match;
    std::regex regex("https?");

    if(regex_match(str, match, regex)) {
        std::cout << "Match" << std::endl;
    }else { 
        std::cout << "No Match" << std::endl;
    }
    return 0;
}

Compiling and running this yields "No Match", and I have no idea why. I originally leaned regexp's with ruby, so I may be misconceived, but this seems like it should match. Changing the regex to "http" makes it match, but I feel like "https?" should match "http" since the question mark means there can be zero or 1 of the character before it.

I'd really appreciate some help here. I've looked at a bunch of the documentation on c++ regular expressions and I can't seem to figure this one out. I have to be missing some small detail.

Any help would be great.

Thanks

Jtvd78
  • 4,135
  • 5
  • 20
  • 21
  • 2
    When I [run](https://wandbox.org/permlink/vSubTrCUKy4LvGGD) it, I get Match. – Paul Rooney Apr 13 '18 at 02:13
  • Matched for me on g++ (MinGW.org GCC-6.3.0-1) 6.3.0, which compiler are you using? – squill25 Apr 13 '18 at 02:15
  • I am using WSL. Running g++ --version gives me: g++ (Ubuntu 4.8.5-2ubuntu1~14.04.1) 4.8.5, which seems to be madly behind – Jtvd78 Apr 13 '18 at 02:16
  • 1
    https://stackoverflow.com/questions/12530406/is-gcc-4-8-or-earlier-buggy-about-regular-expressions " was implemented and released in GCC 4.9.0". Does WSL support newer versions of the compiler? – squill25 Apr 13 '18 at 02:18
  • 2
    Thanks for the help, guys. I don't think I would have solved this on my own. WSL runs a full copy of Ubuntu, so it should support a newer version. I'll install it and report back here with results. – Jtvd78 Apr 13 '18 at 02:23

0 Answers0