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

问题描述

我正在尝试将单词与周围带有可选大括号的单词匹配。即诸如“ {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)\}|)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...