【发布时间】:2013-06-12 13:36:57
【问题描述】:
我正在为我的应用程序编写加载过程,它涉及从文件中读取数据并创建具有适当属性的适当对象。
该文件由以下格式的连续条目(由换行符分隔)组成:
=== OBJECT TYPE ===
<Property 1>: Value1
<Property 2>: Value2
=== END OBJECT TYPE ===
其中的值通常是由任意字符、换行符等组成的字符串。
我想创建一个std::regex,它可以匹配这种格式,并允许我使用std::regex_iterator将每个对象依次读入文件。
但是,我无法创建匹配这种格式的正则表达式;我查看了 ECMAScript 语法并按以下方式创建了我的正则表达式,但它与我的测试应用程序中的字符串不匹配:
const std::regex regexTest( "=== ([^=]+) ===\\n([.\\n]*)\\n=== END \\1 ===" );
并且在以下测试应用程序中使用它时,它无法将正则表达式与字符串匹配:
int main()
{
std::string testString = "=== TEST ===\n<Random Example>:This is a =test=\n<Another Example>:Another Test||\n=== END TEST ===";
std::cout << testString << std::endl;
const std::regex regexTest( "=== ([^=]+) ===\\n([.\\n]*)\\n=== END \\1 ===" );
std::smatch regexMatch;
if( std::regex_match( testString, regexMatch, regexTest ) )
{
std::cout << "Prefix: \"" << regexMatch[1] << "\"" << std::endl;
std::cout << "Main Body: \"" << regexMatch[2] << "\"" << std::endl;
}
return 0;
}
【问题讨论】:
-
你用的是什么编译器?您是否知道
str::regex在某些编译器中没有(完全/根本)实现?g++特别是(我上次检查过)。 -
@Qtax 我正在使用 Microsoft Visual Studio 2012 和附带的标准库实现,据我所知,它提供了
std::regex和相关函数的完整实现。跨度> -
@Shaktal 你可以尝试删除部分表达式(以获取匹配的部分)以查看哪个部分破坏了模式?
标签: c++ regex c++11 ecmascript-5 standard-library