这是我的代码的一部分
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
但是现在,正则表达式总是返回false,我在许多在线正则表达式检查器上甚至在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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句