簡體   English   中英

如何使用regex_token_iterator <std::string::iterator> 通過迭代器本身獲取原始字符串的子匹配位置?

[英]How to use regex_token_iterator<std::string::iterator> get submatch's position of original string by the iterator itself?

下面是在“此主體有潛艇作為子序列”中找到“ \\ b(sub)([^] *)”的代碼。 但是我也想通過regex_token_iterator本身知道那些子匹配在原始字符串中的位置。 結果應為5、19、34。

// regex_token_iterator example
#include <iostream>
#include <string>
#include <regex>

int main ()
{
  std::string s ("this subject has a submarine as a subsequence");
  std::regex e ("\\b(sub)([^ ]*)");   // matches words beginning by "sub"

  // default constructor = end-of-sequence:
  std::regex_token_iterator<std::string::iterator> rend;

  std::cout << "entire matches:"; 
  std::regex_token_iterator<std::string::iterator> a ( s.begin(), s.end(), e );
  while (a!=rend) std::cout << " [" << *a++ << "]";
  std::cout << std::endl;

  return 0;
}

輸出:
整個附件:[主題] [潛艇] [子序列]

*a在字符串s上返回一對兩個迭代器。 您可以嘗試以下方法:

std::cout << " [" << *a++ << ' ' << a->first - s.begin() << "]";

或這個

std::cout << " [" << *a++ << ' ' <<  std::distance(s.begin(), a->first) << "]";

暫無
暫無

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

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