我正在使用 boost.xpressive 静态模板构建动态连接成最终表达式的正则表达式。
动态版本有一个可变宽度的重复,但由于在 int vector 中操作,我确实需要使用静态结构。
我确实需要创建 repeat<N,M>
其中 N
和 M
不是常量。
怎么做?
最佳答案
不幸的是,C++ 只允许您传递编译时已知的模板参数(参见 here )又名 constant expressions .
在这种情况下,这意味着输入到 repeat<N, M>
中的值必须是文字或常量表达式,因此您不能只输入任何 int
你的程序。
在没有看到任何代码的情况下很难给出更具体的建议,但您似乎正在尝试创建一个匹配例如 n
的正则表达式某些组/文字的重复,其中 n
在编译时还不知道(即,取决于程序的某些输入)。
这似乎是一个奇怪的用例,毕竟正则表达式通常是编译时常量(这就是 boost-xpressive 存在的原因)。
我建议改用动态(普通)正则表达式。无论如何,正则表达式都是编译(预处理以加速正则表达式引擎实现中的匹配)。
一般一个正则表达式生成一次,然后多次用于匹配不同的字符串。因此,就性能而言,预处理步骤通常可以忽略不计。
编辑
根据您的要求,这是一个动态 版本,包含在 main
中, 哪个
基于参数的匹配:
#include <iostream>
#include <sstream>
#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
int main(int argc, char* argv[])
{
smatch what;
int min_match = std::stoi(argv[1]);
int max_match = std::stoi(argv[2]);
std::ostringstream expr_buf;
expr_buf << "a{" << min_match
<< ","
<< max_match
<< "}"
<< "b";
sregex rex = sregex::compile(expr_buf.str());
std::string value = argv[3];
if(regex_match(value, what, rex))
{
std::cout << "There was a complete match" << std::endl;
}
else
{
std::cout << "There was no complete match" << std::endl;
}
return 0;
}
例如:
./main 1 3 "aaab" -> "There was a complete match"
./main 1 3 "cab" -> "There was no complete match"
./main 4 5 "aaab" -> "There was no complete match"
关于c++ - 使用 boost.xpressive 重复变量 min/max,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57010737/