1. 程式人生 > 實用技巧 >正則表示式(regex)

正則表示式(regex)

//regex_search()的集合是一組匹配集合,通常表示為一個smatch:
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
using namespace std; 

void use()
{
    ifstream in("file.txt");    //輸入檔案
    if(!in) cerr << "no file\n";
    
    regex pat{R"(\w{2}\s*\d{5}(-\d{4})?)"};        //
美國郵政編碼模式 int lineno=0; for(string line; getline(in,line);){ ++lineno; smatch matches; //匹配的字串儲存在這裡 if(regex_search(line,matches,pat)){ cout << lineno << ": " << matches[0] << '\n'; //完整匹配結果 if(1<matches.size() && matches[1
].matched) cout << "\t: " << matches[1] << '\n'; //子匹配 } } } int main() { use(); return 0; } ---------------------------------------------------------------------------------- //regex_match的使用 bool is_identifier(const string& s) { regex pat{R
"([_[:alpha:]]\w*)"}; //也可寫為:regex pat{"[_[:alpha:]]\\w*"}; return regex_match(s,pat); }