簡體   English   中英

如何使用C ++代碼檢查指定的字符串是否為有效的URL

[英]How to check a specified string is a valid URL or not using C++ code

沒有任何可能的方法來檢查指定的字符串是否是有效的url。 該解決方案必須使用c ++,並且無需互聯網即可使用。

示例字符串是

good.morning
foo.goo.koo
https://hhhh
hdajdklbcbdhd
8881424.www.hfbn55.co.in/sdfsnhjk
://dgdh24.vom
dfgdfgdf(2001)/.com/sdgsgh
\adiihsdfghnhg.co.inskdhhj
aser//www.gtyuh.co.uk/kdsfgdfgfrgj

選擇一個類似/^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([az\\.]{2,6})([\\/\\w \\.-]*)*\\/?$/

如果您沒有C ++ 11,請使用std regexboost regex

if (std::regex_match ("http://subject", std::regex("^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$") )) {
  // ...
}

您可以使用regex 什么是正則表達式。

使用C ++ 11,regex內置在STD庫regex c ++ 11中

如果由於某種原因不能使用C ++ 11,則可以使用boost庫。

無論如何,您可以使用以下方法檢查網址的模式:

#include <regex> //require c++11
// ...

// regex pattern
std::string pattern = "https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)";

// Construct regex object
std::regex url_regex(pattern);

// An url-string for example
std::string my_url = "http://www.google.com/img.png";

// Check for match
if (std::regex_match(my_url, url_regex) == true) {
  std::cout << "This is a well-formed url\n";
} else {
  std::cout << "Ill-formed url\n";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM