C++11中正则表达式测试


VC++2010已经支持regex了, 可以用来编译下述代码.

  1. #include <string>   
  2. #include <regex>   
  3. #include <iostream>   
  4. using namespace std;  
  5.   
  6. /* 测试C++11中的正则表达式. */  
  7. int main()  
  8. {  
  9.     //定义正则表达式,匹配时间格式   
  10.     regex testRegex("[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}");   
  11.   
  12.     //要匹配的字符串   
  13.     string strText("OTA LOG SFTCH/MPA Stream 2/Reservation Accept  07:23:50.580 Channel: 147, Pilot PN: 232");   
  14.   
  15.     cmatch result; //结果   
  16.   
  17.     //search 是匹配子字符串, match 是匹配整个字符串   
  18.     if (regex_search(strText.c_str(), result, testRegex, regex_constants::format_default))  
  19.     {  
  20.         cout << result.str() << endl;  
  21.     }  
  22.     else  
  23.     {  
  24.         cout << "fail." << endl;     
  25.     }  
  26. }  

相关内容