下面是在“这个主题有一个潜艇作为子序列”中找到“\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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
整个 amtches:[subject] [submarine] [subsequence]