gpt4 book ai didi

C++ regex_match 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:09:54 26 4
gpt4 key购买 nike

这是我的部分代码

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

我尝试将我从文件中读取的行与它分开 - 行看起来像:

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

我想从中提取部分 - 例如对于第一行 foo.bar = 15,我想以这样的方式结束:

a = foo
b = bar
c = 15

但是现在,regex 总是返回 false,我在许多在线 regex 检查器上测试过它,甚至在 visual studio 中,它运行良好,我需要一些不同的 C++ regex_match 语法吗?我正在使用 visual studio 2013 社区

最佳答案

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

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

#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 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30445048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com