让每个正则表达式与它们的位置一一匹配
Get every regex match one by one with their positions
我需要获取所有正则表达式匹配项及其位置。
例如,我有一个正则表达式:
std::regex r("(a)|(b)|(c)");
这个输入文本:
std::string text("abcab");
现在我想在每个循环中循环匹配,我可以访问一个匹配中的所有匹配。所以在第一个循环中,我可以在0位置得到"a",在3位置得到"a"。在第二个循环中,它将是"b"在1,"b"位于4。在第三个循环中,它在位置2是"c"。我该怎么做?
目前,我分别拥有每个regex部分(用于(a)
、(b)
和(c)
的regex),并逐一查看它们。但它们有很多,所以我正在寻找更好/更快的解决方案。
您可以声明字符串向量来存储捕获的值,然后检查匹配的替代分支,并将其添加到相应的向量中。
这是一个C++演示:
#include <string>
#include <iostream>
#include <regex>
using namespace std;
int main() {
std::regex r("(a)|(b)|(c)");
std::string s = "abcab";
std::vector<std::string> astrings; // Declare the vectors to
std::vector<std::string> bstrings; // populate with the contents
std::vector<std::string> cstrings; // of capturing groups
for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
i != std::sregex_iterator();
++i)
{
std::smatch m = *i;
if (m[1].matched) { // Check if Group 1 matched and
astrings.push_back(m[1].str()); // Put a value into a string vector
}
else if (m[2].matched) { // Check if Group 2 matched and
bstrings.push_back(m[2].str()); // Put a value into b string vector
}
else if (m[3].matched) { // Check if Group 3 matched and
cstrings.push_back(m[3].str()); // Put a value into c string vector
}
}
// Printing vectors - DEMO
for (auto i: astrings)
std::cout << i << ' ';
std::cout << "n";
for (auto i: bstrings)
std::cout << i << ' ';
std::cout << "n";
for (auto i: cstrings)
std::cout << i << ' ';
return 0;
}
您也可以考虑在声明regexp时使用std::regex_constants::optimize
标志(请参阅Galik的注释)。
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么我的点没有在 OpenGL 中绘制鼠标所在的位置?
- 如何将元素添加到向量的字符串位置
- 如何选择在 csv 文件中输出的位置
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 如何在特定位置追加 json 文件
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 让每个正则表达式与它们的位置一一匹配