使用正则表达式查找第一个匹配C++索引
Find index of first match using C++ regex
我正在尝试使用正则表达式在C++中编写一个拆分函数。到目前为止,我已经想出了这个;
vector<string> split(string s, regex r)
{
vector<string> splits;
while (regex_search(s, r))
{
int split_on = // index of regex match
splits.push_back(s.substr(0, split_on));
s = s.substr(split_on + 1);
}
splits.push_back(s);
return splits;
}
我想知道的是如何填写注释行。
您只需要更多一点,但请参阅下面代码中的注释。男人的技巧是使用匹配对象,这里std::smatch
因为你在std::string
上匹配,记住你匹配的位置(不仅仅是你做了):
vector<string> split(string s, regex r)
{
vector<string> splits;
smatch m; // <-- need a match object
while (regex_search(s, m, r)) // <-- use it here to get the match
{
int split_on = m.position(); // <-- use the match position
splits.push_back(s.substr(0, split_on));
s = s.substr(split_on + m.length()); // <-- also, skip the whole match
}
if(!s.empty()) {
splits.push_back(s); // and there may be one last token at the end
}
return splits;
}
这可以像这样使用:
auto v = split("foo1bar2baz345qux", std::regex("[0-9]+"));
并会给你"foo", "bar", "baz", "qux"
.
std::smatch
是std::match_results
的专业化,此处有参考文档。
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 查找最接近的大于当前数字的数字的索引
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- D3D11-将混合权重和索引传递到顶点着色器
- 将转换字符键入 int 以用作向量C++的索引
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何为圆环创建索引
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 查找字符在两个索引之间出现的次数
- Azure Kinect 使用正文索引映射裁剪正文
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 数组索引重载错误
- 如何在 std::vector 中找到<bool>哪些索引是真的?