Text and Parsing Utilities
Regex Extract Code
A regular expression can extract a structured part of a text record when the format is predictable.
Regex Extract Code
regex_extract_code.cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string ticket = ;
std::regex pattern("([A-Z]+)-([0-9]+)");
std::smatch match;
bool ok = std::regex_match(ticket, match, pattern);
std::string prefix = ok ? match[1].str() : "none";
std::string number = ok ? match[2].str() : "0";
std::cout << "ok=" << ok << std::endl;
std::cout << "prefix=" << prefix << std::endl;
std::cout << "number=" << number << std::endl;
return 0;
}
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string ticket = ;
std::regex pattern("([A-Z]+)-([0-9]+)");
std::smatch match;
bool ok = std::regex_match(ticket, match, pattern);
std::string prefix = ok ? match[1].str() : "none";
std::string number = ok ? match[2].str() : "0";
std::cout << "ok=" << ok << std::endl;
std::cout << "prefix=" << prefix << std::endl;
std::cout << "number=" << number << std::endl;
return 0;
}
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string ticket = ;
std::regex pattern("([A-Z]+)-([0-9]+)");
std::smatch match;
bool ok = std::regex_match(ticket, match, pattern);
std::string prefix = ok ? match[1].str() : "none";
std::string number = ok ? match[2].str() : "0";
std::cout << "ok=" << ok << std::endl;
std::cout << "prefix=" << prefix << std::endl;
std::cout << "number=" << number << std::endl;
return 0;
}
regex
`std::regex` describes a text pattern.
match group
Parentheses in a regex capture part of a match so the program can use it separately.