如何使用STD :: Regex

How to use std::regex?

本文关键字:Regex STD 何使用      更新时间:2023-10-16

我正在使用 c 引物5th 学习C 。下面的代码从P729复制。

#include <iostream>
#include <regex>
#include <string>
int main()
{
    // find the characters ei that follow a character other than c
    std::string pattern("[^c]ei");
    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
    std::regex r(pattern);
//  ~~~~~~~~~~~^~~~~~~~~~~ where the exception was thrown.
    std::smatch results;
    std::string test_str = "receipt freind theif receive";
    if (regex_search(test_str, results, r))
        std::cout << results.str() << std::endl;
    return 0;
}

运行它时,会抛出一个例外:

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Press <RETURN> to close this window...

通过逐步调试,我发现它是从bits/regex_compiler.h中构造对象r时抛出的:

  template<typename _InIter, typename _TraitsT>
    bool
    _Compiler<_InIter, _TraitsT>::
    _M_bracket_expression()
    {
      if (_M_match_token(_ScannerT::_S_token_bracket_begin))
    {
      _RMatcherT __matcher(_M_match_token(_ScannerT::_S_token_line_begin),
                   _M_traits);
      if (!_M_bracket_list(__matcher)
          || !_M_match_token(_ScannerT::_S_token_bracket_end))
        __throw_regex_error(regex_constants::error_brack);
     // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      _M_stack.push(_StateSeq(_M_state_store,
                  _M_state_store._M_insert_matcher(__matcher)));
      return true;
    }
      return false;
    }

ok。上面的代码完全超出了我能理解的。这就是我到目前为止尝试的。有人可以告诉我这里有什么锣吗?如何修复它?

更新:我正在使用的编译器:

gcc version 4.8.1 (Ubuntu 4.8.1-2ubuntu1~13.04)

您需要使用最小版本的G 4.9正确使用正则拨号。(您可以使用较低版本进行编译,但已损坏)

您可以从他们的身边下载G 4.9。GCC网站
之后尝试:
G 49 -STD = C 0x -static -libstdc 。

我尝试为您搜索更多有关它的信息。

编辑:G 49,由于原因,该版本4.9在构建后不能默认。