c++ - boost::regex, match_results::operator[] - 神秘的 "sub += 2"行

标签 c++ regex boost boost-regex

我在从 boost::match_results 类访问子匹配时遇到问题。 当我在调试器中检查程序时,match_results::m_subs 数组包含的正是我所期望的:

  • [0] 是完全匹配。
  • [1] 还有子匹配。它们完全符合预期。

但是,当我尝试使用 operator[] 和从 1 开始的子匹配索引访问子匹配时,我没有得到我想要的。原因隐藏在boost源中:

const_reference operator[](int sub) const
   {
      if(m_is_singular && m_subs.empty())
         raise_logic_error();
      sub += 2;                                             //< WTF?
      if(sub < (int)m_subs.size() && (sub >= 0))
      {
         return m_subs[sub];
      }
      return m_null;
   }

我对此很困惑。文档说我只是使用 [n] 访问第 n 个子匹配,但在代码中,到处都有这个奇怪的偏移量。

请告诉我我没疯:)

已检查的 boost 版本:1.54 和 1.53

最佳答案

match_results.hpp 中定义的 boost::match_results 类的 m_subs vector 属性的前两个元素保留用于存储前缀和后缀。它们的确切含义是:

m_subs[0]           - suffix
m_subs[0].first     - the end position of the match
m_subs[0].second    - the end position of the input text
m_subs[0].matched   - m_subs[0].first != m_subs[0].second
m_subs[1]           - prefix
m_subs[1].first     - the start position of the input text
m_subs[1].second    - the start position of the match
m_subs[1].matched   - m_subs[1].first != m_subs[1].second

捕获组$0的匹配位置存储在m_subs[2],$1在m_subs[3]等,可以通过[0],[1]等通过match_results类引用。这就是为什么你可以看到 magic number 2 在几个地方添加。

看看 match_results 的 suffixprefix 方法是如何实现的:

   const_reference prefix() const
   {
      if(m_is_singular)
         raise_logic_error();
      return (*this)[-1];
   }

   const_reference suffix() const
   {
      if(m_is_singular)
         raise_logic_error();
      return (*this)[-2];
   }

由于这种情况已经持续了很长一段时间,所以我不会很快假设这是导致您的特定问题的原因。如果您需要更多帮助,请提出另一个包含 SSCCE 的问题概述您的问题。

附言你没疯(上面的代码真的很糟糕)

关于c++ - boost::regex, match_results::operator[] - 神秘的 "sub += 2"行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351253/

相关文章:

c++ - 修复 C++ 中的 "this"错误

java - 不包括方括号的正则表达式

Java RegEx 字符串包含在引号内,但有附加要求

regex - 为什么这个 python 正则表达式返回不匹配?

c++ - 取消连接是 boost::asio

c++ - 使用 Boost 确保模板参数继承自某个类

c++ - 迭代 C++ 可变参数模板类型列表

c++ - 函数调用运算符重载的参数太多

c++ - 基于模板参数的模板参数的类特化

c++ - *您*使用 C++ ABC 构造函数做什么?