如何在C ++ 11中使用正则表达式匹配多个模式 [英] How to match multiple patterns with a regex in C++ 11
问题描述
假设有一个名为path的字符串,需要匹配多个模式.正则表达式字符串如下:
Suppose there is a string named path that needs to match multiple patterns. The regular expression string is as follows:
std::string regexString="(/api/Attachment)|(/api/Attachment/upload)|(/api/Attachment/download)|(/api/v1/ApiTest)|(/api/v1/ApiTest/get/[^/]*/[^/]*)|(/api/v1/ApiTest/[^/]*/List)";
匹配的代码如下:
std::smatch result;
if (std::regex_match(path, result, regexString))
{
for (size_t i = 1; i < result.size(); i++)
{
/// Question: Is there any better way to find the sub-match index without using a loop?
if (!result[i].matched)
continue;
if (result[i].str() == path)
{
std::cout<<"Match a pattern with index "<<i<<std::endl;
/// Do something with it;
break;
}
}
}
else
{
std::cout<<"Match none"<<std::endl;
}
上面的程序可以工作,但是考虑到大量的模式,其中的循环有点难看且效率低下.如代码中的注释所示,我的问题是有没有一种方法可以找到不使用循环的子匹配索引?
The above program works, but considering a large number of patterns, the loop in it is a bit ugly and inefficient. As the comments in the code show, my question is is there a way to find the sub-match index without using loops?
任何评论将不胜感激,谢谢!
Any comments would be greatly appreciated, thank you!
推荐答案
尝试仅使用覆盖所有变体的单个交替.在下面的模式中,我还交替关闭捕获.这给我们留下了相当简单的匹配逻辑.如果 smatch
结果没有有一个条目,则它应该是具有完整匹配路径的单个条目.否则,它应该为空.
Try just using a single alternation which covers all variations. In the pattern below, I also turn off capturing in the alternation. This leaves us with fairly straightforward matching logic. If the smatch
result does have an entry, then it should be a single entry with the entire matching path. Otherwise, it should be empty.
std::string regexString="/api/(?:Attachment|Attachment/upload|Attachment/download|v1/ApiTest|v1/ApiTest/get/[^/]*/[^/]*|v1/ApiTest/[^/]*/List)";
std::string s ("/api/Attachment/upload");
std::regex e (regexString);
std::smatch sm;
std::regex_match (s,sm,e);
if (sm.size() > 0) {
std::cout << "found a matching path: " << sm[0];
}
found a matching path: /api/Attachment/upload
这篇关于如何在C ++ 11中使用正则表达式匹配多个模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!