Reputation: 55
my pattern seems to match external regex tester but my program fails. what's wrong with my code ? I would appreciate any comments
my code:
std::smatch matches;
s = "y=a^b,z=(y+76),k=(z|p)";
for (int t=0; t<4; t++) {
try {
std::regex expr ( "((\\w+)=\\((\\w+)([\\|&\\^\\+\\-\\*])(\\w+)\\))" , regex_constants::extended ); // regex::extended|regex_constants::basic
std::regex_match(s, matches, expr);
if ( matches.empty() ) puts ("No Match !");
Upvotes: 2
Views: 1347
Reputation: 47448
First, GCC did not support <regex>
until 4.9, you will have to upgrade or switch to another compiler (clang or MSVC, for example) or use boost.regex.
Second, regex_match attempts to match the entire string, it will fail. You need regex_search or regex_iterator
Third, your regex is not a valid POSIX ERE (at least according to libc++ and gcc 4.9), just drop the regex_constants:
#include <regex>
#include <iostream>
int main()
{
std::smatch matches;
std::string s = "y=a^b,z=(y+76),k=(z|p)";
std::regex expr(R"((\w+)=\((\w+)([|&^+*-])(\w+)\))"); // simplified a bit
for(auto it = std::sregex_iterator(s.begin(), s.end(), expr);
it != std::sregex_iterator();
++it)
{
std::cout << "Found a match: " << it->str() << "\n";
std::smatch m = *it;
std::cout << "prefix=[" << m.prefix() << "]\n";
for(std::size_t n = 0; n < m.size(); ++n)
std::cout << " m[" << n << "]=[" << m[n] << "]\n";
std::cout << "suffix=[" << m.suffix() << "]\n";
}
}
online demo: http://coliru.stacked-crooked.com/a/559d3bca554517c6
Upvotes: 5