C++11 正则表达式,非贪婪匹配

5

我在使用 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


为什么你用 \\{ 转义左花括号,但不转义右花括号? - Bobulous
@Bobulous 这是一个正则表达式的特殊字符,它帮助重复前面的模式。 - Avinash Raj
1
我认为你不应该使用std::regex::extended,它会使你的正则表达式符合POSIX ERE标准,而这个标准不支持懒惰量词。 - Wiktor Stribiżew
啊,好的,正则表达式认为左花括号是一个特殊字符,但右花括号不是。我之前不知道这一点。 - Bobulous
1个回答

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接