无法在 C++ 中使用正则表达式从字符串中获取所有子字符串
Can't get all substrings from a string using RegEx in C++
我想获取与此表达式匹配的所有子字符串:1[0]+1
std::string str = "0011011000001";
std::regex rx ("1[0]+1");
std::smatch res;
std::regex_search(str, res, rx);
for (size_t i=0; i<res.size(); i++)
std::cout<<res[i]<<std::endl;
但它只返回我第一个子字符串。我做错了什么?
你应该这样做来获取所有子字符串:
while (std::regex_search (str,res,rx)) {
std::cout <<res[0] << std::endl;
str = res.suffix().str();
}
或者您可以使用 std::regex_iterator 获取所有子字符串,如下所示:
std::regex_iterator<std::string::iterator> rit ( str.begin(), str.end(), rx);
std::regex_iterator<std::string::iterator> rend;
while (rit != rend) {
std::cout << rit->str() << std::endl;
++rit;
}
但是当字符串为"00110101000001"时,它仍将输出"101"和"1000001",因为第一个匹配项会消耗部分字符串。如果要查找所有重叠的匹配项,则需要一个支持 Lookaround 断言的正则表达式实现。Python 确实:
>>> re.findall(r'(?=(1[0]+1))', '00110101000001')
['101', '101', '1000001']
(?=... 匹配如果...匹配下一个,但不消耗任何字符串。这称为前瞻断言。例如,Isaac(?=Asimov)只有在后面跟着"Asimov"时才匹配"Isaac"。
使匹配不贪婪...
std::regex rx ("(1[0]+1)?");
相关文章:
- 从C字符串中获取奇怪的字符串长度
- 获取字符串的长度并将其分配给数组
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 调用CreateProcess()并获取字符串的返回值
- 从字符串中获取结构的大小
- Cryptopp:获取密码输入的填充字符串
- 获取无效的字符串大小
- 获取 OID(类型::b_oid)作为 MongoDB C++驱动程序中的字符串
- C ++编译器如何获取argv字符串的长度
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 如何使用字符串获取用户控制台输入
- 通过字符串获取小部件
- 无法从字符串获取数字输入
- 在C++的静态方法中将类名作为字符串获取
- 从设备实例路径字符串获取设备实例 DWORD
- HRESULT到字符串(获取文档路径)C++
- 如何从http请求体字符串获取文件名
- 如何使用带有垃圾字符的子字符串获取字符串
- 通过字符串获取对话框项的可能性
- 有没有办法将 WinAPI 错误标志作为字符串获取