如何迭代std::string中所有匹配的正则表达式,使其在c++11 std::regex中的起始位置
how to iterate all regex matches in a std::string with their starting positions in c++11 std::regex?
我知道从std::string获得regex匹配的两种方法,但我不知道如何获得具有各自偏移量的所有匹配。
#include <string>
#include <iostream>
#include <regex>
int main() {
using namespace std;
string s = "123 apples 456 oranges 789 bananas oranges bananas";
regex r = regex("[a-z]+");
const sregex_token_iterator end;
// here I know how to get all occurences
// but don't know how to get starting offset of each one
for (sregex_token_iterator i(s.cbegin(), s.cend(), r); i != end; ++i) {
cout << *i << endl;
}
cout << "====" << endl;
// and here I know how to get position
// but the code is finding only first match
smatch m;
regex_search ( s, m, r );
for (unsigned i=0; i< m.size(); ++i) {
cout << m.position(i) << endl;
cout << m[i] << endl;
}
}
首先,为什么是记号迭代器?没有任何标记的子表达式要迭代。
第二,position()是匹配的成员函数,所以:#include <string>
#include <iostream>
#include <regex>
int main() {
std::string s = "123 apples 456 oranges 789 bananas oranges bananas";
std::regex r("[a-z]+");
for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
i != std::sregex_iterator();
++i )
{
std::smatch m = *i;
std::cout << m.str() << " at position " << m.position() << 'n';
}
}
live at coliru: http://coliru.stacked-crooked.com/a/492643ca2b6c5dac
相关文章:
- 如何使 std::正则表达式匹配 Utf8
- C++11 (MSVS2012) 正则表达式在多行 std::string 中查找文件名
- std::正则表达式捕获组语法错误
- std::正则表达式转义"+"符号
- 使用 STD 正则表达式标记逗号分隔的列表
- 对 std::string 执行正则表达式搜索和替换
- 仅查找第一个 std::正则表达式有效匹配
- 减少 std::正则表达式编译时间 C++
- 将Javascript正则表达式模式转换为C++std::regex的规则
- C++ std::正则表达式多行语法
- std::正则表达式无法按预期工作
- C++ - 在长时间的多行匹配期间,STD 正则表达式在 MSVC 中崩溃
- C++ std::正则表达式 查找多个匹配项
- 使用 std::正则表达式进行简单的 RX 是一种很好的做法
- c++中的STD正则表达式
- 如何使用正则表达式删除std::wstring中特定短语的所有实例
- Microsoft 的 std::正则表达式的实现
- C++ 2011 std::正则表达式根本不起作用
- 将正则表达式存储在变量(std::string)中
- c++ STD正则表达式问号问题