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

标签 c++ regex backreference

我正在尝试将单词与可选的大括号匹配。即类似于“{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)\}|)

关于c++ - C++中的正则表达式,带有反向引用和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64281644/

相关文章:

C++ SDL 二维跳跃(重力)

regex - 匹配时如何使一个词优先于其他词?

javascript - 正则表达式从完整 url 中删除文件名

python - Python 中的命名反向引用 (?P=name) 问题重新

Java 正则表达式错误 - 使用组引用进行向后查找

c++ - 类型检查 protected 标记 union

c++ - 什么是 (void (*) (void))((uint32_t)&__STACK_END)?

python - 迁移到 numpy api 1.7

regex - 替换给定 unicode 字符串中的所有表情符号

python重新反向引用重复元素