微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否可以将 std::regex 和 std::match_results 与自定义字符串类型一起使用?

如何解决是否可以将 std::regex 和 std::match_results 与自定义字符串类型一起使用?

我正在处理一个具有自定义字符串类型 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 "";
  }
}

但是如您所见,在返回值时,我必须将 cmatchs std::string 转换回 MyString。这根本不是什么大问题,但我注意到 std::match_results 是大量模板化的,所以我想知道是否有可能以某种方式将 MyString 放在其模板参数中以获得已经作为 {{1} }.

有可能吗?如果是,怎么做?

解决方法

是的,如果您提供迭代器,则可以使用它们,这些方法需要这些方法。

要使用 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 的要求。

为了满足迭代器的要求,意味着你应该提供一个类,它实现了递增、递减和解引用迭代器的接口。迭代器的最简单示例是指针,以防您的 MyString 将所有 chars 存储在单个数组中。要调用 regex_match,您需要两个指针 - 在数组的开头,一个指向最后一个元素之后的下一个元素。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。