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