我正在为我的应用程序编写加载过程,它涉及从文件中读取数据并创建具有适当属性的适当对象。
该文件由以下格式的连续条目(由换行符分隔)组成:
=== 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;
}
最佳答案
您的问题比看起来要简单得多。这:
const std::regex regexTest( "=== ([^=]+) ===\\n((?:.|\\n)*)\\n=== END \\1 ===" );
在 clang++/libc++ 上完美运行。 \n
似乎不适合 ECMAscript 正则表达式中的 []
括号。如果您想在字符串中查找多个正则表达式实例,请记住使用 while regex_search
而不是 if regex_match
!
关于c++ - 用于多行字符串的 ECMAScript 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17133296/