求助一个正则表达式的写法

cadinfo 2018-10-28 11:24:51
需要用广义匹配字符串来过滤文件名,但是类似boost这样的库只支持正则表达式,
所以想通过正则表达式修改广义匹配字符串,使之转成合理的正则表达式

下面是我网上找的代码,测试不通过,所以请精通正则的朋友帮忙修改下

std::string dos_wildcard_to_regex(std::string s)
{
//const char *szReg = "(\\w+)://((\\w+\\.)*\\w+)((/\\w*)*)(/\\w+\\.\\w+)?";
//boost::regex x(szReg);

static const boost::regex e("([.\\[{()\\+|^$])|(?)|(*)"); //<=======这句直接不通过,exception
return regex_replace(s, e, "(?1\\$1)(?2.)(?3.*)", boost::regex_constants::match_default |
boost::regex_constants::format_all);
}
...全文
116 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
cadinfo 2018-10-28
  • 打赏
  • 举报
回复
参考网上的JavaScript,自己改写了一个,有需要的拿去不谢

std::string dos_wildcard_to_regex(std::string s)
{
//static const boost::regex e("([.\\[{()\\+|^$])|(?)|(*)"); //这里有错
//return regex_replace(s, e, "(?1\\$1)(?2.)(?3.*)", boost::regex_constants::match_default |
// boost::regex_constants::format_all);

//先自己参考写了个不借助regex_replace的,已经测试通过
const static char ESCAPES[] = { '$', '^', '[', ']', '(', ')', '{', '|', '+', '\\', '.', '<', '>' };
std::string result = "^";

bool escaped = false;
int escnum = _countof(ESCAPES);
for (int i = 0; i < s.length(); i++) {
char ch = s[i];
escaped = false;
for (int j = 0; j < escnum; j++) {
if (ch == ESCAPES[j]) {
result += "\\";
result += ch;
escaped = true;
break;
}
}

if (!escaped) {
if (ch == '*') {
result += ".*";
} else if (ch == '?') {
result += ".";
} else {
result += ch;
}
}
}
result += "$";
return result;
}

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧