CPP +正则表达式验证URL

use*_*960 5 c c++ regex mfc visual-c++

我想在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必须检查&无效网址为"/\MyWebSite /\ISAPIWEBSITE /\Denypage"之间的'\'字符的.aspx /"

  2. http://cu-241.dell-tech.co.in//////MyWebSite/ISAPIWEBSITE/Denypage.aspx/ =由于多次输入"///////",Regx必须检查并使URL无效在网址中.

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

我们如何开发满足上述条件的通用正则表达式.请通过提供一个正则表达式帮助我们,这个表达式将处理CPP中的上述场景{MFC}

Cir*_*sta 10

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

它表明^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?你可以获得子匹配:

  scheme    = $2
  authority = $4
  path      = $5
  query     = $7
  fragment  = $9
Run Code Online (Sandbox Code Playgroud)

例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后:

./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
Run Code Online (Sandbox Code Playgroud)

  • 不可否认,这不是用于验证,而是用于将正确的URI拆分为其部分.它甚至不会检测最简单的情况,例如未编码的空间. (3认同)

dav*_*vka 0

查看http://gskinner.com/RegExr/,右侧有一个社区选项卡,您可以在其中找到贡献的正则表达式。有一个 URI 类别,不确定您是否能准确找到您需要的内容,但这是一个好的开始