c++實現正則表示式匹配
阿新 • • 發佈:2019-02-17
c++11之後封裝了自己的正則表示式,直接包含檔案即可使用,利用regex類宣告物件初始化正則表示式,regex expressionName (“正則表示式”);正則表示式具體語法參考這裡;regex_match()方法進行匹配,匹配成功返回1,失敗返回0;cmatch和smatch類分別存放char*和string型別的結果,遍歷即可獲得;
// regex_match example
#include <iostream>
#include <string>
#include <regex>
int main ()
{
if (std::regex_match ("subject" , std::regex("(sub)(.*)") ))
std::cout << "string literal matched\n";//字串匹配
const char cstr[] = "subject";
std::string s ("subject");
std::regex e ("(sub)(.*)");
if (std::regex_match (s,e))
std::cout << "string object matched\n";//字元物件匹配
if ( std::regex_match ( s.begin(), s.end(), e ) )
std ::cout << "range matched\n";//選擇特定的位置進行匹配
std::cmatch cm; // same as std::match_results<const char*> cm;
std::regex_match (cstr,cm,e);
std::cout << "string literal with " << cm.size() << " matches\n";
std::smatch sm; // same as std::match_results<string::const_iterator> sm;
std::regex_match (s,sm,e);
std::cout << "string object with " << sm.size() << " matches\n";
std::regex_match ( s.cbegin(), s.cend(), sm, e);
std::cout << "range with " << sm.size() << " matches\n";
// using explicit flags:
std::regex_match ( cstr, cm, e, std::regex_constants::match_default );
std::cout << "the matches were: ";
for (unsigned i=0; i<sm.size(); ++i) {
std::cout << "[" << sm[i] << "] ";
}
std::cout << std::endl;
return 0;
}
小問題總結:
1.上圖正則表示式的一些限制,如icase: Case insensitive(忽略大小寫)regex expressionName (“正則表示式”,std::regex::icase).
2.正則表示式在c++程式碼中注意轉義字元的使用,由於c++程式碼本身的轉移功能,需要兩次“\”的操作才能實現,如正則表示式需要匹配“\”,正則表示式為“\”,則咋c++程式碼中需要“\\”,第一個“\”轉義說明第二個“\”為“\”,同理第三個“\”轉義說明第四個“\”為“\”,獲得正則表示式“\”.