簡體   English   中英

是否可以將 std::regex 和 std::match_results 與自定義字符串類型一起使用?

[英]Is it possible to use std::regex and std::match_results with custom string type?

我正在開發一個具有自定義字符串類型MyString的項目。 我可以像這樣匹配它:

MyString getMatch() {
  static const std::regex MyRegularExpression(R"RX(^blah=([a-z0-9]+)$)RX");
  const MyString str = "blah=25";
  std::cmatch match;
  if (std::regex_match(str.GetConstCharPtr(), match, MyRegularExpression))
  {
    return MyString(match[1].str().c_str());
  }
  else {
    return "";
  }
}

但是正如您所看到的,我必須在返回值時從cmatchstd::string轉換回MyString 這根本不是什么大問題,但我注意到std::match_results被大量模板化,所以我想知道是否有可能以某種方式將MyString放入其模板 arguments 以獲得已經作為MyString的匹配結果。

可能嗎? 如果是,該怎么做?

是的,如果您提供迭代器,您可以使用它們,這是這些方法所期望的。

要使用regex_matchmatch_results ,您需要提供一個迭代器,它可以雙向移動。

template< 
    class BidirIt,
    class Alloc, class CharT, class Traits >
bool regex_match( BidirIt first, BidirIt last,
              std::match_results<BidirIt,Alloc>& m,
              const std::basic_regex<CharT,Traits>& e,
              std::regex_constants::match_flag_type flags =
              std::regex_constants::match_default );

template<
    class BidirIt,
    class Alloc = std::allocator<std::sub_match<BidirIt>>
> class match_results;

在哪里,

BidirIt必須滿足LegacyBidirectionalIterator的要求。

為了滿足迭代器的要求,意味着您應該提供一個 class,它實現了遞增、遞減和取消引用迭代器的接口。 最簡單的迭代器示例是指針,以防您的MyString將所有chars存儲在單個數組中。 要調用regex_match您將需要兩個指針 - 在數組的開頭,一個指向最后一個元素之后的下一個。

暫無
暫無

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

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