C ++ regex_match不工作 [英] C++ regex_match not working

查看:179
本文介绍了C ++ regex_match不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码的一部分

bool CSettings::bParseLine ( const char* input )
{
    //_asm INT 3


    std::string line ( input );
    std::size_t position = std::string::npos, comment;

    regex cvarPattern ( "\\.([a-zA-Z_]+)" );
    regex parentPattern ( "^([a-zA-Z0-9_]+)\\." );
    regex cvarValue ( "\\.[a-zA-Z0-9_]+[ ]*=[ ]*(\\d+\\.*\\d*)" );
    std::cmatch matchedParent, matchedCvar;


    if ( line.empty ( ) )
        return false;

    if ( !std::regex_match ( line.c_str ( ), matchedParent, parentPattern ) )
        return false;

    if ( !std::regex_match ( line.c_str ( ), matchedCvar, cvarPattern ) )
        return false;
...
}

我尝试用它分隔行从文件读取 - 行如下:

I try to separate with it lines which I read from file - lines look like:

foo.bar = 15
baz.asd = 13
ddd.dgh = 66

,我想从中提取零件 - 例如对于第一行foo.bar = 15,我想结束如下:

and I want to extract parts from it - e.g. for 1st line foo.bar = 15, I want to end up with something like:

a = foo
b = bar
c = 15

但现在,regex总是返回false,在线regex检查,甚至在visual studio,它的工作很好,我需要一些不同的语法为C + + regex_match?我使用visual studio 2013社区

but now, regex is returning always false, I tested it on many online regex checkers, and even in visual studio, and it's working great, do I need some different syntax for C++ regex_match? I'm using visual studio 2013 community

推荐答案

问题是 std :: regex_match 必须匹配整个字符串,但您只尝试匹配它的一部分。

The problem is that std::regex_match must match the entire string but you are trying to match only part of it.

您需要使用 std :: regex_search 或更改您的正则表达式一次匹配所有三个部分:

You need to either use std::regex_search or alter your regular expression to match all three parts at once:

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

const auto test =
{
      "foo.bar = 15"
    , "baz.asd = 13"
    , "ddd.dgh = 66"
};

int main()
{
    const std::regex r(R"~(([^.]+)\.([^\s]+)[^0-9]+(\d+))~");
    //                     (  1  )  (   2  )       ( 3 ) <- capture groups

    std::cmatch m;

    for(const auto& line: test)
    {
        if(std::regex_match(line, m, r))
        {
            // m.str(0) is the entire matched string
            // m.str(1) is the 1st capture group
            // etc...
            std::cout << "a = " << m.str(1) << '\n';
            std::cout << "b = " << m.str(2) << '\n';
            std::cout << "c = " << m.str(3) << '\n';
            std::cout << '\n';
        }
    }
}

正则表达式: https://regex101.com/r/kB2cX3/2

输出:

a = foo
b = bar
c = 15

a = baz
b = asd
c = 13

a = ddd
b = dgh
c = 66

这篇关于C ++ regex_match不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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