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