正则表达式不匹配

BNR*_*BNR 2 c++ regex cygwin c++11

我的模式似乎与外部正则表达式测试仪匹配,但我的程序失败了。我的代码有什么问题?我将不胜感激任何评论

我的代码:

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 !");
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Cub*_*bbi 5

首先,GCC<regex>直到 4.9才支持,您必须升级或切换到另一个编译器(例如,clang 或 MSVC)或使用boost.regex

其次,regex_match尝试匹配整个字符串,它会失败。你需要regex_searchregex_iterator

第三,您的正则表达式不是有效的 POSIX ERE(至少根据 libc++ 和 gcc 4.9),只需删除 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";
    }
}
Run Code Online (Sandbox Code Playgroud)

在线演示:http : //coliru.stacked-crooked.com/a/559d3bca554517c6