我在使用 C++11 正则表达式时遇到了一些问题,我认为它与贪婪性有关。
以下是一个小样例:
#include <stdio.h>
#include <string>
#include <regex>
int main (void)
{
std::string in="{ab}{cd}[ef]{gh}[ij][kl]"; // the input-string
std::regex rx1 ("(\\{.+?})(.*)", std::regex::extended); // non-greedy?
std::smatch match;
if (regex_match (in, match, rx1))
{
printf ("\n%s\n", match.str(1).c_str());
}
return 0;
}
我期望
{ab}
用于输出。 但是我得到了
。{ab}{cd}[ef]{gh}
如果我使用.+而不是.+?来进行贪婪匹配,希望得到的结果是可以预测的。使用非贪婪匹配应该可以解决这个问题,对吧?
那么我的想法有什么问题吗?感谢您的帮助!
Chris
\\{
转义左花括号,但不转义右花括号? - Bobulousstd::regex::extended
,它会使你的正则表达式符合POSIX ERE标准,而这个标准不支持懒惰量词。 - Wiktor Stribiżew