CPP +正则表达式验证URL
CPP + Regular Expression to Validate URL
我想在c++{MFC}中构建一个正则表达式来验证URL。
正则表达式必须满足以下条件:
有效的URL: -http://cu-241.dell-tech.co.in/MyWebSite/ISAPIWEBSITE/Denypage.aspx/http://www.google.comhttp://www.google.co.in
无效URL: -
-
http://cu-241.dell-tech.co.in/MyWebSite/ISAPIWEBSITE/Denypage.aspx/= Regx必须检查&在"/MyWebSite/ISAPIWEBSITE/Denypage.aspx/"
-
http://cu-241.dell-tech.co.in//////MyWebSite/ISAPIWEBSITE/Denypage.aspx/= Regx必须检查&
由于URL中有多个"///////"条目而使URL无效。 http://news.google.co.in/%5Cnwshp?hl=en&tab=wn = Regex必须检查&使额外插入%5C &的URL无效;% 2 f性格。
如何开发满足上述条件的泛型正则表达式?请提供一个正则表达式来帮助我们,它将在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
查看http://gskinner.com/RegExr/,右侧有一个社区选项卡,您可以在其中找到贡献的正则表达式。有一个URI分类,不确定你能找到你需要的但这是一个很好的开始
使用下面的正则表达式,您可以简单地过滤掉大多数不正确的url:
int main(int argc, char* argv[]) {
std::string url(argv[1]);
std::regex urlRegex(R"(^https?://[0-9a-z.-]+(:[1-9][0-9]*)?(/[^s]*)*$)");
if (!std::regex_match(value, urlRegex)) {
throw Poco::InvalidArgumentException(
"Malformed URL: "" + value + "". "
"The URL must start with http:// or https://, "
"the domain name should only contain lowercase alphanumeric characters, '.' and '-', "
"the port should not start with 0, "
"and the URL should not contain any whitespace.");
}
}
检查URL是否以http://
或https://
开头,域名是否只有lowercase alphanumeric characters
和'.'
和'-'
,检查端口是否以0开头(例如0123),并允许任何端口号和任何不包含空格的路径/查询字符串。
但是为了绝对确定URL是有效的,您可能最好对URL进行解析。我不建议尝试用regex覆盖所有场景(包括路径、查询、片段的正确性),因为这将非常困难。
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- LibGit2 SSH身份验证失败
- Vulkan验证层不断在VkQueuePresentKHR()上抛出图像布局错误
- constexpr上下文中std::initializer_list的验证
- 如何使用url确定网站协议
- 下载URL中的所有文件
- 使用libcurl提交批量url的正确BING Api POST url是什么
- 正在验证c++中用户的整数输入
- 加密++验证大文件签名
- C++卡验证问题
- 验证指针链
- 此代码验证公式是什么意思?
- cin 的十进制输入验证?
- 简单的 HTML 验证器
- 密码长度验证 (c++)
- 将所有 URL 组织在类中的一个位置
- 使用OpenSSL和C 来验证JWT的确切基本64 URL解码规则和实现
- 使用std::regex调用abort()来验证URL
- CPP +正则表达式验证URL