C++11 正则表达式,非贪婪
C++11 RegEx, non-greedy
我对 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}
如果我贪婪但不使用 ?在.+之后
应该让它不贪心,对吧?
那么我的想法有什么问题呢?
感谢您的帮助!
克里斯
您需要删除 std::regex::extended
, it makes your regex POSIX ERE 兼容,并且正则表达式风格不支持惰性量词。
std::regex rx1("(\{.+?})(.*)");
我对 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}
如果我贪婪但不使用 ?在.+之后 应该让它不贪心,对吧?
那么我的想法有什么问题呢? 感谢您的帮助!
克里斯
您需要删除 std::regex::extended
, it makes your regex POSIX ERE 兼容,并且正则表达式风格不支持惰性量词。
std::regex rx1("(\{.+?})(.*)");