gpt4 book ai didi

c++ - CPP + 正则表达式来验证 URL

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:12:49 26 4
gpt4 key购买 nike

我想在 c++{MFC} 中构建一个验证 URL 的正则表达式。

正则表达式必须满足以下条件。

有效网址:- http://cu-241.dell-tech.co.in/MyWebSite/ISAPIWEBSITE/Denypage.aspx/http://www.google.com http://www.google.co.in

无效网址:-

  1. http://cu-241.dell-tech.co.in/\MyWebSite/\ISAPIWEBSITE/\Denypage.aspx/= Regx 必须检查无效 URL 作为“/\MyWebSite/\ISAPIWEBSITE/\Denypage.aspx/”之间的“\”字符

  2. http://cu-241.dell-tech.co.in//////MyWebSite/ISAPIWEBSITE/Denypage.aspx/ = 由于 url 中有多个“///////”条目,Regx 必须检查并使 URL 无效。

  3. http://news.google.co.in/%5Cnwshp?hl=en&tab=wn = 正则表达式必须检查并使 URL 无效以额外插入 %5C 和 %2F 字符。

我们如何开发满足上述条件的通用正则表达式。请帮助我们提供一个正则表达式来处理 CPP{MFC}

中的上述情况

最佳答案

您是否尝试过使用 RFC 3986建议?如果您能够使用 GCC-4.9,那么您可以直接使用 <regex> .

它指出 ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?你可以得到子匹配:

  scheme    = $2
authority = $4
path = $5
query = $7
fragment = $9

例如:

int main(int argc, char *argv[])
{
std::string url (argv[1]);
unsigned counter = 0;

std::regex url_regex (
R"(^(([^:\/?#]+):)?(//([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)",
std::regex::extended
);
std::smatch url_match_result;

std::cout << "Checking: " << url << std::endl;

if (std::regex_match(url, url_match_result, url_regex)) {
for (const auto& res : url_match_result) {
std::cout << counter++ << ": " << res << std::endl;
}
} else {
std::cerr << "Malformed url." << std::endl;
}

return EXIT_SUCCESS;
}

然后:

./url-matcher http://localhost.com/path\?hue\=br\#cool

Checking: http://localhost.com/path?hue=br#cool
0: http://localhost.com/path?hue=br#cool
1: http:
2: http
3: //localhost.com
4: localhost.com
5: /path
6: ?hue=br
7: hue=br
8: #cool
9: cool

关于c++ - CPP + 正则表达式来验证 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5620235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com