C++ std::regex using lookahead fails

巧了我就是萌 提交于 2019-12-11 15:01:31

问题


I need to parse a txt file, from disk. So i have firstly made an example, to test regex.

This is my example code:

std::string txt("paragraph:\r\nthis is the text file\r\ni need only this data\r\nnotthis");
std::smatch m;
std::regex rt("paragraph:([\\S\\s](?=notthis))");
std::regex_search(txt, m, rt);

std::cout << m.str(1) << std::endl;

So i'm trying to parse until notthis, but returned match m is a failed match. If i do the regex like this: std::regex rt("paragraph:([\\S\\s]+)"); it works fine, but i get the whole text:

this is the text file
i need only this data
notthis

I haven't used many regex before, but i have been told that c++ using ecmascript syntax, but in the documentation, it seems that the pattern for lookahead is the same, and only lookbehinds are not supported. How can i make a lookahead in the ecmascript?


回答1:


Use as follow:

#include <iostream>
#include <string>
#include <regex>

int main()
{
std::string txt("paragraph:\r\nthis is the text file\r\ni need only this data\r\nnotthis");
std::smatch m;
std::regex rt("paragraph:([\\S\\s]+(?=notthis))");
std::regex_search(txt, m, rt);

std::cout << m.str(1) << std::endl;
}


来源:https://stackoverflow.com/questions/52797969/c-stdregex-using-lookahead-fails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!