C++ 中的正则表达式,带有反向引用和条件

Regex in C++ with back-references and conditionals

我正在尝试匹配带有可选大括号的单词。 IE。类似“{word}”或“word”的东西。

我想用条件表达式来实现。

({)?(word)(?(1)?}|)

where:
({)?      optional 1st group
(word)    mandatory word
(?(1)}|) if-then-else condition, if the first group was found, it matches the same group again

我不确定 C++ 中反向引用和 if-then-else 条件的正确语法。

到目前为止我得到了什么:

#include <iostream>
#include <string>
#include <regex>


int
main()
{
  std::regex re("(\{)?(word)(\?(\1)\}|)");


  // Possible options
  std::vector<std::string> toMatch = {
    "{word}",
    "{word",
    "word"
    }; 

  for (int i = 0; i < toMatch.size(); ++i)
  {
    std::smatch ss;
    std::regex_match(toMatch[i], ss, re);

    std::cout << i << " : " << ss.size() << std::endl;

    for (int j = 0; j < ss.size(); ++j)
    {
        std::cout << "group >   '" << ss[j] << "'" << std::endl;
    }
  }

  return 0;
}

输出:

0 : 0
1 : 5
group >   '{word'
group >   '{'
group >   'word'
group >   ''
group >   ''
2 : 5
group >   'word'
group >   ''
group >   'word'
group >   ''
group >   ''

第一个字符串根本不匹配,第二个字符串匹配,因为它缺少尾随括号。条件和反向引用机制似乎在这里不起作用。

std::regex 使用的 default ECMAScript regex flavor(以及所有其他,主要是 POSIX 风格)不支持条件构造。

您的代码片段中的模式将适用于 Boost。从你的例子来看,你的正则表达式应该看起来像 (\{)?(word)(?(1)\}|).