C++ std::regex 使用前瞻失败 [英] C++ std::regex using lookahead fails

查看:31
本文介绍了C++ std::regex 使用前瞻失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从磁盘解析一个 txt 文件.所以我首先做了一个例子,来测试正则表达式.

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

这是我的示例代码:

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;

所以我试图解析直到 notthis,但返回的匹配 m 是一个失败的匹配.如果我像这样执行正则表达式: std::regex rt("paragraph:([\\S\\s]+)"); 它工作正常,但我得到了整个文本:

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

我之前没有使用过很多正则表达式,但有人告诉我 c++ 使用 ecmascript 语法,但在文档中,前瞻的模式似乎是相同的,并且仅不支持后视.我如何在 ecmascript 中进行前瞻?

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?

推荐答案

使用方法如下:

#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;
}

这篇关于C++ std::regex 使用前瞻失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆