C++ Regex Helper
You write std::regex
that works the first try? Well, I am not nearly as good as you, and I find it helpful to iterate my patterns until I get it right:
// compile with `g++ -std=c++20 -o regex-sandbox regex-sandbox.cpp`
#include <iostream>
#include <regex>
#include <string>
void usage(const char* proggy)
{
std::cout << "usage: " << proggy << " <target_string> <regex_string>" << std::endl;
}
int main(int argc, char** argv)
{
if (argc < 3) {
usage(argv[0]);
} else {
std::string target(argv[1]);
std::smatch results;
std::regex pattern(argv[2]);
std::regex_search(target, results, pattern);
if (!results.empty()) {
std::cout << "matched: " << results.size() << std::endl;
for (size_t i = 0; i < results.size(); ++i) {
std::cout << "\t" << i << ":\t'" << std::string(results[i]) << "'" << std::endl;
}
} else {
std::cout << "no match." << std::endl;
}
}
return 0;
}
Compile it with a compiler that speaks regular expressions, then you can run it to display help:
./regex-sandbox
usage: ./regex-sandbox <target_string> <regex_string>
Where target_string
is the source text you want to match against, and regex_string
is your regex pattern. If pattern matched something, it'll tell you what they are; otherwise it'll report "no match." This way you can tweak the last argument until you match the items you were looking for. For example, to extract host name and port number from URL:
./regex-sandbox "http://wackymango.com:80" "^http://(.+):(\\d+)$"
matched: 3
0: 'http://wackymango.com:80'
1: 'wackymango.com'
2: '80'
I hope you find it useful. You have the source and you can do whatever you want with it.