简体   繁体   English

找不到C ++正则表达式搜索模式

[英]c++ regex search pattern not found

Following the example here I wrote following code: 按照此处的示例我编写了以下代码:

using namespace std::regex_constants;
std::string str("{trol,asdfsad},{safsa, aaaaa,aaaaadfs}");
std::smatch m;
std::regex r("\\{(.*)\\}");   // matches anything between {}

std::cout << "Initiating search..." << std::endl;
while (std::regex_search(str, m, r)) {
    for (auto x : m) {
        std::cout << x << " ";
    }
    std::cout << std::endl;
    str = m.suffix().str();
}

But to my surprise, it doesn't find anything at all which I fail to understand. 但是令我惊讶的是,它根本找不到我无法理解的任何东西。 I would understand if the regex matches whole string since .* is greedy but nothing at all? 我想知道如果.*是贪婪的,那么正则表达式是否匹配整个字符串,但是什么也没有? What am I doing wrong here? 我在这里做错了什么?

To be clear - I know that regexes are not suitable for Parsing BUT I won't deal with more levels of bracket nesting and therefore I find usage of regexes good enough. 需要明确的是-我知道正则表达式不适合解析,但我不会处理更多级别的括号嵌套,因此我发现正则表达式的用法足够好。

If you want to use basic posix syntax, your regex should be 如果您想使用基本的posix语法,则您的正则表达式应为

{\\(.*\\)}

If you want to use default ECMAScript, your regex should be 如果要使用默认的ECMAScript,则您的正则表达式应为

\\{(.*)\\}

with clang and libc++ or with gcc 4.9+ (since only it fully support regex) your code give: 使用clang和libc ++或gcc 4.9+(因为它完全支持正则表达式),您的代码给出:

Initiating search...
{trol,asdfsad},{safsa, aaaaa,aaaaadfs} trol,asdfsad},{safsa, aaaaa,aaaaadfs 

Live example on coliru 关于大肠杆菌的实时示例

Eventually it turned out to really be problem with gcc version so I finally got it working using boost::regex library and following code: 最终,事实证明这确实是gcc版本的问题,所以我终于使用boost :: regex库和以下代码使其工作了:

std::string str("{trol,asdfsad},{safsa,aaaaa,aaaaadfs}");
boost::regex rex("\\{(.*?)\\}", boost::regex_constants::perl);
boost::smatch result;

while (boost::regex_search(str, result, rex)) {
    for (uint i = 0; i < result.size(); ++i) {
        std::cout << result[i] << " ";
    }
    std::cout << std::endl;
    str = result.suffix().str();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM