使用C++在Linux平台下实现的简易的字符串识别,类型包括常见进制、base64编码、URL等格式。
问题
输入:不定长字符串
输出:数据类型
例:
输入:0x1A2B
输出:十六进制
思路
使用正则表达式进行格式判断;
使用libcurl发送HTTP(默认GET)请求,验证URL是否可达
代码
头文件
#include <iostream> #include <regex> #include <string> #include <curl/curl.h>
方法
//Determine if the string is binary bool isBinaryString(const std::string& str) { std::regex BinaryPattern("^[01]+$"); return std::regex_match(str, BinaryPattern); } //Determine if the string is octal bool isOctalString(const std::string& str){ std::regex OctalPattern("^0[0-7]+$"); return std::regex_match(str,OctalPattern); } //Determine if the string is hex bool isHexString(const std::string& str){ std::regex HexPattern("^(0[xX])?[0-9a-fA-F]+$"); return std::regex_match(str,HexPattern); } //Determine if the string is base64 bool isBase64String(const std::string& str){ std::regex Base64Pattern("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$"); return std::regex_match(str,Base64Pattern); } //Determine if the string is a valid URL format (using regex) bool isURLString(const std::string& str){ std::regex UrlPattern(R"(^(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|])"); return std::regex_match(str,UrlPattern); } // check if the URL is reachable (using libcurl) // send HTTP request using libcurl to check if the URL is reachable bool isURLReachable(const std::string& url){ CURL* curl = curl_easy_init(); if(!curl){ std::cerr<<"Failed to initialize libcurl."<<std::endl; return false; } // set the URL to check curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); // set timeout for the request curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5L); // 5 seconds timeout // perform the request CURLcode res = curl_easy_perform(curl); // clean up curl_easy_cleanup(curl); // check if the request was successful return (res == CURLE_OK); }
主函数
int main(int argc, char* argv[]) { if(argc < 2){ std::cout<<"enter your parameter!"<<std::endl; return 1; } std::string input = argv[1]; if(isBinaryString(input)){ std::cout<<"the string is binary."<<std::endl; }else if(isOctalString(input)){ std::cout<<"the string is octal."<<std::endl; }else if(isHexString(input)){ std::cout<<"the string is hexadecimal."<<std::endl; }else if(isBase64String(input)){ std::cout<<"the string is base64"<<std::endl; }else if(isURLString(input)){ std::cout<<"the string is a valid URL format."<<std::endl; // check if the URL is reachable if(isURLReachable(input)){ std::cout<<"the URL is reachable."<<std::endl; }else{ std::cout<<"the URL is unreachable."<<std::endl; } }else{std::cout<<"the string format is unknown."<<std::endl; } return 0; }
编译
安装libcurl开发包
sudo apt-get update sudo apt-get install libcurl4-openssl-dev
编译时需要连接curl库
g++ CodePattern.cpp -o CodePattern -lcurl
测试
运行