簡體   English   中英

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

[英]boost::regex, match_results::operator[] - Mysterious “sub += 2” line

我從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個子匹配,但是在代碼中,到處都有這個奇怪的偏移量。

請告訴我我不是瘋了:)

經檢查的增強版本:1.54和1.53

match_results.hpp中定義的boost::match_results類的m_subs矢量屬性中的前兩個元素保留用於存儲前綴和后綴。 它們的確切含義是:

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]等中,可以通過match_results類通過[0],[1]等來引用。這就是為什么看到魔術數字 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的問題,概述您的問題。

PS你不是瘋了(上面的代碼真的很糟糕)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM