CPP +正则表达式验证URL

CPP + Regular Expression to Validate URL

本文关键字:URL 验证 正则表达式 CPP      更新时间:2023-10-16

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

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

有效的URL: -http://cu-241.dell-tech.co.in/MyWebSite/ISAPIWEBSITE/Denypage.aspx/http://www.google.comhttp://www.google.co.in

无效URL: -

  1. http://cu-241.dell-tech.co.in/MyWebSite/ISAPIWEBSITE/Denypage.aspx/= Regx必须检查&在"/MyWebSite/ISAPIWEBSITE/Denypage.aspx/"

  2. http://cu-241.dell-tech.co.in//////MyWebSite/ISAPIWEBSITE/Denypage.aspx/= Regx必须检查&

  3. 由于URL中有多个"///////"条目而使URL无效。
  4. http://news.google.co.in/%5Cnwshp?hl=en&tab=wn = Regex必须检查&使额外插入%5C &amp的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覆盖所有场景(包括路径、查询、片段的正确性),因为这将非常困难。