将字符串作为正则表达式模式输入传递。 (非标量错误)

时间:2016-01-31 17:55:28

标签: c++ regex string c++11

我正在尝试执行正则表达式搜索,但不是键入模式(例如std :: regex reg =" \。")我想给正则表达式输入字符串。这是我的代码,我将字符串转换为const char *并将其传递给regex_search:

void trigger_regex(string name, string body)
    {

      map<string,string>::iterator it;
      it=test.mydata.find(name);
      if( it == test.mydata.end())
      {
        std::cout<<"REGEX not found"<<endl;
      }
      else
        cout << "Found REGEX with name: " << it->first << " and rule: " << it->second << endl ;

        string subject = body;
        string rule = it -> second;
        const char * pattern = rule.c_str();
        regex reg = (pattern);
        smatch match;    

        while (regex_search (subject,match,reg)) {
          for (auto x:match) std::cout << x << " ";
          std::cout << std::endl;
          body = match.suffix().str();
        }
     }

我收到错误:

  

转换为&#39; const char *&#39;到非标量类型&#st; :: regex {aka   的std :: basic_regex}&#39;要求        regex reg1 =(rule1);

任何帮助吗?

1 个答案:

答案 0 :(得分:1)

如果你看一下,例如this std::regex constructor reference您将看到构造函数仅使用字符串(列表中的第二个构造函数)标记为explicit。这意味着您必须显式使用该构造函数,您只能希望将字符串转换为std::regex对象。

换句话说,解决方案是像这样定义和初始化对象

std::regex reg1{pattern};